python - 如何使用 KMeans 绘制质心

标签 python machine-learning scikit-learn k-means

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

import numpy as np ##Import necassary packages
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
from pandas.plotting import scatter_matrix
from 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 internet
Adult = 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 dataframe
Adult.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()

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

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'。是不是原来的代码不正确,会不会在以后的项目中造成问题?如果是这样,我应该如何将代码更改为我没有收到错误的地方?提前致谢

最佳答案

问题是如果你在没有键的情况下传递参数值,散点函数期望第三个参数是 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'])

关于python - 如何使用 KMeans 绘制质心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61181342/

相关文章:

python - 解决开关 block 中默认标签的移位/减少冲突

networking - 机器学习在计算机网络领域的应用

python - 如何检测 DataFrame 中数据线性变化的连续跨度?

python - 列表的 Pandas 列分隔列

scikit-learn - sklearn、Keras、DeepStack - ValueError : multi_class must be in ('ovo' , 'ovr' )

python - 从系列中删除非数值

python - 获取遗传算法中使用的对象的值

python - 排列列表中的元素,使相似的元素相距最远

python - 打开用于机器学习的 ROOT NTuple 的最快、最节省内存的方法是什么?

python - 在 cross_val_predict 之后对新文档进行分类