gpt4 book ai didi

python - 如何使用 KMeans 绘制质心

转载 作者:行者123 更新时间:2023-12-05 01:12:59 31 4
gpt4 key购买 nike

我正在处理一个数据集并尝试学习如何使用聚类分析和 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com