# 如何在tslearn中提取群集元素

``````from tslearn.utils import save_time_series_txt, load_time_series_txt
import numpy as np
import numpy
import matplotlib.pyplot as plt

from tslearn.clustering import KShape
from tslearn.datasets import CachedDatasets
from tslearn.preprocessing import TimeSeriesScalerMeanVariance
from tslearn.clustering import GlobalAlignmentKernelKMeans
from tslearn.metrics import sigma_gak
from tslearn.clustering import TimeSeriesKMeans
X_train=time_series_dataset
X_train.shape
#np.random.shuffle(X_train)
# For this method to operate properly, prior scaling is required
#seed = 0
#numpy.random.seed(seed)
sz = X_train.shape[1]
# DBA-k-means
print("DBA k-means")
dba_km = TimeSeriesKMeans(n_clusters=3,
n_init=2,
metric="dtw",
verbose=True,
max_iter_barycenter=10)
y_pred = dba_km.fit_predict(X_train)
for yi in range(3):
#plt.subplot(3, 3, 4 + yi)
for xx in X_train[y_pred == yi]:
plt.plot(xx.ravel(), "k-", alpha=.2)
plt.plot(dba_km.cluster_centers_[yi].ravel(), "-")
plt.xlim(0, sz)
#plt.ylim(-1.2,1.5)
plt.text(0.55, 0.85,'Cluster %d' % (yi + 1),
transform=plt.gca().transAxes)
if yi == 1:
plt.title("DBA \$k\$-means")

plt.figure()
for yi in range(3):
#plt.subplot(4, 1, 1 + yi)
#for xx in X_train[y_pred == yi]:
#plt.plot(xx.ravel(), "k-", alpha=.2)
plt.plot(dba_km.cluster_centers_[yi].ravel(), "-")
plt.xlim(0, sz)
#plt.ylim(-1.2,1.5)
plt.title("Cluster %d" % (yi + 1))

plt.tight_layout()
plt.show()

for yi in range(3):
#plt.subplot(3, 3, 4 + yi)
#for xx in X_train[y_pred == yi]:
#plt.plot(xx.ravel(), "k-", alpha=.2)
plt.plot(dba_km.cluster_centers_[yi].ravel(), "-")
``````