绘制一维数据的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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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