+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

如何使用KMeans绘制质心

发布于2020-06-25 17:22     阅读(1047)     评论(1)     点赞(2)     收藏(4)


我正在使用数据集,并试图学习如何使用聚类分析和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'])


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接: https://www.pythonheidong.com/blog/article/429956/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

2 0
收藏该文
已收藏

评论内容:(最多支持255个字符)