IndexError: list index out of range while running KMeans in Python

IndexError: list index out of range while running KMeans in Python

我想运行 Kmeans 聚类算法具有五个特征。 (K=4) 但是,我收到一个索引错误:

> Traceback (most recent call last):   
> File
> "C:\....py", line 756,
> in <module>
>     plt.plot(X[i][0],X[i][1],colors[labels[i]],markersize=10) 
>     IndexError: list index out of range

这是生成错误的代码片段:

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

kmeans = KMeans(n_clusters=4)
kmeans.fit(X)

centroid = kmeans.cluster_centers_
labels = kmeans.labels_

fig = plt.figure(figsize=(9,7), dpi=100)

colors = ["r.","b.","y."]

df_clustering = []

for i in range(len(X)):
   print ("ID:", df_features['id'].loc[[i]].values[0], "coordinate:" , X[i], "label:", labels[i])
   df_clustering.append((df_features['id'].loc[[i]].values[0], labels[i]))

   # below line is generating an error
   plt.plot(X[i][0],X[i][1],colors[labels[i]],markersize=10)

您正在使用 4 个集群,但 colors 的长度为 3。因此对于分配给集群 4 的任何数据点(即 labels[i] == 3),都会有一个 IndexError.