为了账号安全,请及时绑定邮箱和手机立即绑定

如何绘制 KMeans?

如何绘制 KMeans?

犯罪嫌疑人X 2022-10-06 20:03:10
我正在尝试将 MiniBatchKMeans 与更大的数据集一起使用并绘制 2 个不同的属性。我收到一个Keyerror: 2我相信我在for循环中出错但我不确定在哪里。有人可以帮我看看我的错误是什么?我正在运行以下代码:import numpy as np ##Import necessary 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"]print("reviewing dataframe:")print(Adult.head()) #Getting an overview of the dataprint(Adult.shape)print(Adult.dtypes)np.median(Adult['fnlwgt']) #Calculating median for final weight columnTooLarge = Adult.loc[:,'fnlwgt'] > 748495 #Setting a value to replace outliers from final weight column with medianAdult.loc[TooLarge,'fnlwgt']=np.median(Adult['fnlwgt']) #replacing values from final weight Column with the median of the final weight columnAdult.loc[:,'fnlwgt']X = pd.DataFrame()X.loc[:,0] = Adult.loc[:,'age']X.loc[:,1] = Adult.loc[:,'hoursperweek']kmeans = MiniBatchKMeans(n_clusters = 2)kmeans.fit(X)centroids = kmeans.cluster_centers_labels = kmeans.labels_print(centroids)print(labels)colors = ["g.","r."]for i in range(len(X)):    print("coordinate:",X[i], "label:", labels[i])    plt.plot(X.loc[:,0][i],X.loc[:,1][i], colors[labels[i]], markersize = 10)plt.scatter(centroids[:, 0], centroids[:, 1], marker = "x", s=150, linewidths = 5, zorder = 10)plt.show()当我运行for循环时,我只看到散点矩阵中绘制了 2 个数据点。我是否需要以与创建的数据框不同的方式调用这些点?
查看完整描述

1 回答

?
繁花不似锦

TA贡献1851条经验 获得超4个赞

您可以通过不运行循环来单独绘制 32,000 个点中的每一个来避免此问题,这是不好的做法,也是不必要的。您可以简单地传递两个数组来plt.scatter()制作这个散点图,不需要循环。使用这些行:


colors = ["green","red"]


plt.scatter(X.iloc[:,0], X.iloc[:,1], c=np.array(colors)[labels], 

    s = 10, alpha=.1)


plt.scatter(centroids[:, 0], centroids[:, 1], marker = "x", s=150, 

    linewidths = 5, zorder = 10, c=['green', 'red'])

plt.show()

//img1.sycdn.imooc.com//633ec42800016f9a05610434.jpg

您最初的错误是由于对熊猫索引的不当使用造成的。您可以通过这样做来复制您的错误:


df = pd.DataFrame(list('dasdasas'))

df[1]


查看完整回答
反对 回复 2022-10-06
  • 1 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信