如何绘制 KMeans?

我正在尝试将 MiniBatchKMeans 与更大的数据集一起使用并绘制 2 个不同的属性。我收到一个Keyerror: 2我相信我在for循环中出错但我不确定在哪里。有人可以帮我看看我的错误是什么?我正在运行以下代码:


import numpy as np ##Import necessary 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"]


print("reviewing dataframe:")

print(Adult.head()) #Getting an overview of the data

print(Adult.shape)

print(Adult.dtypes)


np.median(Adult['fnlwgt']) #Calculating median for final weight column

TooLarge = Adult.loc[:,'fnlwgt'] > 748495 #Setting a value to replace outliers from final weight column with median

Adult.loc[TooLarge,'fnlwgt']=np.median(Adult['fnlwgt']) #replacing values from final weight Column with the median of the final weight column

Adult.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 个数据点。我是否需要以与创建的数据框不同的方式调用这些点?


犯罪嫌疑人X
浏览 115回答 1
1回答

繁花不似锦

您可以通过不运行循环来单独绘制 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()您最初的错误是由于对熊猫索引的不当使用造成的。您可以通过这样做来复制您的错误:df = pd.DataFrame(list('dasdasas'))df[1]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python