如何使用KMeans绘制质心

我正在处理一组数据,并试图学习如何使用聚类分析和KMeans。我从绘制两个属性的散点图开始,当我添加第三个属性并尝试绘制另一个质心时,出现了错误。我运行的代码如下:

import numpy as np ##Import necassary packagesimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib import stylestyle.use("ggplot")from pandas.plotting import scatter_matrixfrom sklearn.preprocessing import *from sklearn.cluster import MiniBatchKMeans url2="http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data" #Reading in Data from a freely and easily available source on the internetAdult = pd.read_csv(url2, header=None, skipinitialspace=True) #Decoding data by removing extra spaces in cplumns with skipinitialspace=True##Assigning reasonable column names to the dataframeAdult.columns = ["age","workclass","fnlwgt","education","educationnum","maritalstatus","occupation",                   "relationship","race","sex","capitalgain","capitalloss","hoursperweek","nativecountry",                 "less50kmoreeq50kn"]Adult.loc[:, "White"] = (Adult.loc[:, "race"] == "White").astype(int)X = pd.DataFrame()X.loc[:,0] = Adult.loc[:,'age']X.loc[:,1] = Adult.loc[:,'hoursperweek']X.loc[:,2] = Adult.loc[:, "White"]kmeans = MiniBatchKMeans(n_clusters = 3)kmeans.fit(X)centroids = kmeans.cluster_centers_labels = kmeans.labels_print(centroids)print(labels)colors = ["green","red","blue"]plt.scatter(X.iloc[:,0], X.iloc[:,1], X.iloc[:,2], c=np.array(colors)[labels], alpha=.1)plt.scatter(centroids[:, 0], centroids[:, 1],  marker = "x", s=150,     linewidths = 5, zorder = 10, c=['green', 'red','blue'])plt.show()

运行代码是可行的,但似乎不正确,因为只有两个质心被“调用”,但仍然绘制了三个质心。当我将质心散点图更改为:

plt.scatter(centroids[:, 0], centroids[:, 1], centroids[:, 2] marker = "x", s=150,         linewidths = 5, zorder = 10, c=['green', 'red','blue'])

我得到一个 TypeError: scatter() got multiple values for argument 's'。原来的代码是否不正确,将来会不会引起问题?如果是,我应该如何修改代码以避免错误?提前感谢


回答:

问题在于如果你传递没有键的参数值,scatter函数期望第三个参数是s。在你的情况下,第三个参数是质心,并且你又传递了s作为关键字参数。因此,它为s收到了多个值。你需要的是这样的东西。

1) 分配质心的列:centroids_x, centroids_y

centroids_x = centroids[:,0]centroids_y = centroids[:,1]

2) 绘制centroids_x和centroids_y的散点图

plt.scatter(centroids_x,centroids_y,marker = "x", s=150,linewidths = 5, zorder = 10, c=['green', 'red','blue'])

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中创建了一个多类分类项目。该项目可以对…

发表回复

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