gpt4 book ai didi

python - Python 中的 K 均值聚类

转载 作者:太空狗 更新时间:2023-10-30 01:07:05 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com