# K-Means와 Time Series K-Means 차이
기존 K-Means는 2차원 데이터의 K개의 중심을 기준으로 클러스터링을 하게 된다.
주가 데이터처럼 시계열 데이터를 분석하는 경우에는 Time Series K-Means를 하게 되면 시계열 간의 차이를 계산할 수 있게 된다.
# K-Means와 Time Series K-Means 그림 예시
# Time Series K-Means 예제 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
from tslearn.generators import random_walks
from tslearn.clustering import TimeSeriesKMeans
import matplotlib.pyplot as plt
x = random_walks(n_ts=20, sz=32, d=1)
# x plot
fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(projection='3d')
for x_idx in range(x.shape[0]):
xv = [x_idx / x.shape[0]] * x.shape[1]
yv = [i for i in range(x.shape[1])]
zv = x[x_idx].squeeze(-1)
ax.plot(xv, yv, zv)
ax.set_title('random walks x value')
plt.show()
n_clusters = 3
km = TimeSeriesKMeans(n_clusters=n_clusters, metric="dtw", max_iter=50)
pred = km.fit_predict(x)
# time series plot
for c in range(n_clusters):
fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(projection='3d')
for x_idx in range(x.shape[0]):
if pred[x_idx] == c:
xv = [x_idx / x.shape[0]] * x.shape[1]
yv = [i for i in range(x.shape[1])]
zv = x[x_idx].squeeze(-1)
ax.plot(xv, yv, zv)
ax.set_title('cluster number is {}'.format(c))
plt.show()
|
cs |
입력 데이터: (20, 32, 1) 차원의 랜덤 시계열 데이터
TimeSeriesKMeans 함수를 사용하여 시계열 데이터 클러스터링 처리
TimeSeriesKMeans 함수 파라미터 예시
- n_clusters: 군집의 개수
- metric: 시계열 데이터 간의 거리 계산 방식 (종류: ['eudlidean', 'dtw', 'softdtw'])
- max_iter: 최대 반복 시행 횟수
# 입력 데이터 예시
# 결과 데이터 예시
-> 오른쪽 아래로 떨어지는 모양의 시계열 데이터가 묶이는 것을 확인할 수 있음.
-> 오른쪽 위로 올라가는 모양의 시계열 데이터가 묶이는 것을 확인할 수 있음.
-> 오른쪽으로 횡보하는 형태의 시계열 데이터가 묶이는 것을 확인할 수 있음.
위와 같이 시계열 데이터를 특징에 맞게 분류를 할 수 있는 것을 예제를 통해 확인했음.
# tslearn 공식 문서
k-means — tslearn 0.5.3.2 documentation
Note Click here to download the full example code k-means This example uses \(k\)-means clustering for time series. Three variants of the algorithm are available: standard Euclidean \(k\)-means, DBA-\(k\)-means (for DTW Barycenter Averaging [1]) and Soft-D
tslearn.readthedocs.io
# 이후 내용
KMeans, DTW, softDTW를 분석하는 글을 작성하고자 함.
'파이썬 > 데이터분석' 카테고리의 다른 글
EM 알고리즘 (expectation maximization algorithm) (0) | 2023.02.23 |
---|---|
DBSCAN 설명 및 코드 (0) | 2023.02.22 |
pandas duplicate drop시 중복된 값을 평균 만들기 (0) | 2023.02.13 |
datetime index를 통해 pandas DataFrame 생성 (0) | 2023.02.13 |