【发布时间】:2019-09-20 14:29:33
【问题描述】:
我使用 K-Means 聚类绘制了一些数据点。屏幕截图位于“https://imageshack.com/i/pomMJXMkj”。当我可视化这些数据点时,可以清楚地看到许多点不在它们各自的簇中,而这个绿色点就是其中之一,它远离其质心,并且显然非常靠近蓝色质心。根据 K-Means 算法,将点添加到具有最近质心的集群中。但是这里为什么不是这样呢?
下面提到了以下视觉对象的代码,数据集的链接是“https://github.com/Vivek-Nimmagadda/Player-Prediction-Using-Python/blob/master/Bowlers/Bowlers.csv”:
# Importing the Batsmen Dataset
dataset = pd.read_csv('Bowlers\Bowlers.csv')
X = dataset.iloc[:, [1, 2, 3, 4, 5, 6, 7]].values
# Using Elbow Method to find the optimal number of Clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1, 11):
kmeans = KMeans(n_clusters=i, init='k-means++', n_init=10, max_iter=300, random_state=0)
kmeans.fit(X)
wcss.append(kmeans.inertia_)
plt.plot(range(1, 11), wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of Clusters')
plt.ylabel('WCSS')
plt.show()
# Fitting K-Meaens Clustering Algorithm to the Dataset
kmeans = KMeans(n_clusters=4, init='k-means++', n_init=10, max_iter=300, random_state=0)
y_kmeans = kmeans.fit_predict(X)
# Visualising the Clusters
plt.scatter(X[y_kmeans == 0,2], X[y_kmeans == 0,4], s = 100, c = 'blue', label = 'Good Form')
plt.scatter(X[y_kmeans == 1,2], X[y_kmeans == 1,4], s = 100, c = 'purple', label = 'Average Touch')
plt.scatter(X[y_kmeans == 2,2], X[y_kmeans == 2,4], s = 100, c = 'green', label = 'Peek Form')
plt.scatter(X[y_kmeans == 3,2], X[y_kmeans == 3,4], s = 100, c = 'red', label = 'Poor Form')
plt.scatter(kmeans.cluster_centers_[:, 2], kmeans.cluster_centers_[:, 4], s = 150, c = 'cyan', label = 'Centroids')
plt.title('Recent Form of Bowlers Based on their Stats')
plt.xlabel('Wickets')
plt.ylabel('Average')
plt.legend()
plt.show()
我的预期结果是在各自的集群中准确地可视化所有数据点。而它随机显示点。谁能帮我纠正这个错误?
【问题讨论】:
-
您可以尝试在绘图本身中使用 for 循环。此链接可能对您有用。 benalexkeen.com/k-means-clustering-in-python
标签: python machine-learning scikit-learn k-means sklearn-pandas