错误:Python中K均值聚类算法的数据图表不可见

你好,我想实现K均值聚类算法。

为此,我从sample.csv文件中获取数据,并对其应用K均值聚类。这里是我的源代码

## K-Means.py

# clustering datasetimport pandasfrom sklearn.cluster import KMeansfrom sklearn import metricsimport numpy as npimport matplotlib.pyplot as pltvariables = pandas.read_csv("/Users/srikanth/Desktop/sample1.csv")print(variables)x1 = variables[['X']]x2 = variables[['Y']]print(x1)print(x2)plt.plot()plt.xlim([0, 10])plt.ylim([0, 10])plt.title('Dataset')plt.xlabel('X - Values')plt.ylabel('Y - Values')plt.scatter(x1, x2)plt.show()# create new plot and dataplt.plot()X = np.array(list(zip(x1, x2))).reshape(len(x1), 2)colors = ['b', 'g', 'r']markers = ['o', 'v', 's']# KMeans algorithmK = 3kmeans_model = KMeans(n_clusters=K).fit(X)plt.plot()for i, l in enumerate(kmeans_model.labels_):    plt.plot(x1[i], x2[i], color=colors[l], marker=markers[l],ls='None')    plt.xlim([0, 10])    plt.ylim([0, 10])    plt.show()

当我在终端运行上述代码后,输出如下:

Console Output

plots visualization

上面的图片没有显示任何聚类数据图表,所以我想看到我的聚类数据图表的可视化效果。我该如何解决这个问题?我在这个领域是新手。谢谢


回答:

from sklearn.cluster import KMeansfrom sklearn import metricsimport numpy as npimport matplotlib.pyplot as pltvariables = pandas.read_csv("/Users/srikanth/Desktop/sample1.csv")print(variables)x1 = variables[['X']]x2 = variables[['Y']]plt.plot()plt.xlim([150, 190])plt.ylim([40, 90])plt.title('Dataset')plt.xlabel('X - Values')plt.ylabel('Y - Values')plt.scatter(x1, x2)plt.show()

它为10个点生成的散点图是:

enter image description here

对于使用kmeans聚类模型的代码,你是为模型中的每个标签绘图,这将产生10个图表。只需更改限制就能实现魔法效果。

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…

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

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

发表回复

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