绘制一维数据的KMeans聚类和分类

我使用KMeans来对三个具有不同特征的时间序列数据集进行聚类。为了确保可重现性,我在这里分享数据这里

这是我的代码

这样,给定一个新的数据点(带有quotientquotient_times),我希望通过构建每个数据集来堆叠这两个转换后的特征quotientquotient_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')

这会产生以下图表。

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")

这会生成以下图表,显示原始数据,每个点根据聚类成员身份着色。

points coloured by cluster

Related Posts

在使用k近邻算法时,有没有办法获取被使用的“邻居”?

我想找到一种方法来确定在我的knn算法中实际使用了哪些…

Theano在Google Colab上无法启用GPU支持

我在尝试使用Theano库训练一个模型。由于我的电脑内…

准确性评分似乎有误

这里是代码: from sklearn.metrics…

Keras Functional API: “错误检查输入时:期望input_1具有4个维度,但得到形状为(X, Y)的数组”

我在尝试使用Keras的fit_generator来训…

如何使用sklearn.datasets.make_classification在指定范围内生成合成数据?

我想为分类问题创建合成数据。我使用了sklearn.d…

如何处理预测时不在训练集中的标签

已关闭。 此问题与编程或软件开发无关。目前不接受回答。…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注