如何使用KMeans绘制质心图

问题描述 投票:0回答:1

我正在使用数据集,并试图学习如何使用聚类分析和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'。原始的错误代码是否会在以后的项目中引起问题?如果是这样,我应该如何将代码更改为没有收到错误的地方?在此先感谢

python machine-learning scikit-learn k-means
1个回答
0
投票

问题是如果您传递不带键的参数值,则分散函数期望第三个参数为s。在您的情况下,第三个参数是质心,然后再次将s作为关键字参数传递。因此它具有多个值s。您需要的是这样的。

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

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

2)绘制质心x和质心y的散点图>

plt.scatter(centroids_x,centroids_y,marker = "x", s=150,linewidths = 5, zorder = 10, c=['green', 'red','blue'])
© www.soinside.com 2019 - 2024. All rights reserved.