python - Python 中的 K 均值聚类

标签 python cluster-analysis k-means

import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans


x = [916,684,613,612,593,552,487,484,475,474,438,431,421,418,409,391,389,388,
    380,374,371,369,357,356,340,338,328,317,316,315,313,303,283,257,255,254,245,
    234,232,227,227,222,221,221,219,214,201,200,194,169,155,140]

kmeans = KMeans(n_clusters=4)
a = kmeans.fit(np.reshape(x,(len(x),1)))
centroids = kmeans.cluster_centers_

labels = kmeans.labels_

print(centroids)
print(labels)

colors = ["g.","r.","y.","b."]

for i in range(len(x)):
    plt.plot(x[i], colors[labels[i]], markersize = 10)

plt.scatter(centroids[:, 0], marker = "x", s = 150, linewidths = 5, zorder = 10)
plt.show()

上面的代码显示了 4 个簇,但它们绝对不是我想要的。

我也遇到了一个错误,这让情况变得更糟。我得到的输出如下图所示。

我得到的错误是:TypeError: scatter() missing 1 required positional argument: 'y' 错误不是什么大问题,因为我不喜欢我拥有的东西。

Clusters Output

下图是我希望集群输出的样子。

Cluster I want

最佳答案

你的数据是一维的(一条线),如果你想像帖子中的图片那样在二维中可视化,你应该使用二维或多维数据,例如[[1, 3], [2,3], [1,5]]. 在 k-means 之后,它们被分成 k 个簇,您可以使用 scatter 来可视化输出。对了,scatter取x和y,scatter是二维可视化。

我建议你看看Orange,一个python数据挖掘工具。您可以通过拖放来执行 k-means。

enter image description here

并轻松可视化 k-means 的输出。

enter image description here

祝你好运!数据挖掘很有趣 :-)

关于python - Python 中的 K 均值聚类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33458834/

相关文章:

Python + OpenCV 使用 Kmeans 进行颜色分割

Python - 将格式化行导入为索引列表对象

python - 计算没有。使用 OpenCV 将图像中的黑色像素转换为白色像素

OS.walk 的 C++ 替代方案

c++ - PCL : How to delete deviations from a point cloud?

optimization - 哪个目标是优化的簇内距离总和或 MSE?

r - R 中的 k 均值返回值

python - Django : Groups in production

r - 通过 WeightedCluster 包进行多 channel 序列分析

c++ - 改进目标检测的建议