我使用KMeans
来对三个具有不同特征的时间序列数据集进行聚类。为了确保可重现性,我在这里分享数据这里。
这是我的代码
这样,给定一个新的数据点(带有quotient
和quotient_times
),我希望通过构建每个数据集来堆叠这两个转换后的特征quotient
和quotient_times
,使用KMeans
来确定它属于哪个cluster
。
k_means.labels_
给出这样的输出array([1, 1, 0, 1, 2, 1, 0, 0, 2, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0], dtype=int32)
最后,我想使用plt.plot(k_means, ".",color="blue")
来可视化聚类,但得到了这样的错误:TypeError: float() argument must be a string or a number, not 'KMeans'
。我们如何绘制KMeans
聚类?
回答:
你实际上在寻找的是一系列值,这些值之间被认为属于某个给定类别。用这种方式使用KMeans来分类一维数据是相当不寻常的,尽管它确实有效。正如你所注意到的,你需要将输入数据转换为二维数组才能使用该方法。
k_means = KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300, n_clusters=3, n_init=10, n_jobs=None, precompute_distances='auto', random_state=0, tol=0.0001, verbose=0)quotient_2d = quotient.reshape(-1,1)k_means.fit(quotient_2d)
在后续的分类(预测)步骤中,你将再次需要quotient_2d
。
首先,我们可以绘制质心,因为数据是一维的,x轴上的点是任意的。
colors = ['r','g','b']centroids = k_means.cluster_centers_for n, y in enumerate(centroids): plt.plot(1, y, marker='x', color=colors[n], ms=10)plt.title('Kmeans cluster centroids')
这会产生以下图表。
要获取点的聚类成员身份,将quotient_2d
传递给.predict
。这将返回一个表示类别成员身份的数字数组,例如:
>>> Z = k_means.predict(quotient_2d)>>> Zarray([1, 1, 0, 1, 2, 1, 0, 0, 2, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0], dtype=int32)
我们可以使用它来过滤原始数据,分别以不同颜色绘制每个类别。
# Plot each class as a separate colourn_clusters = 3 for n in range(n_clusters): # Filter data points to plot each in turn. ys = quotient[ Z==n ] xs = quotient_times[ Z==n ] plt.scatter(xs, ys, color=colors[n])plt.title("Points by cluster")
这会生成以下图表,显示原始数据,每个点根据聚类成员身份着色。