通過從頭開始使用這個 k 均值聚類,我如何在照片的散點圖上繪制 k=3 的初始隨機聚類中心?
鳶尾花資料集的
這里嘗試將給定的目標名稱與 kmeans 近似值一起顯示。請注意,kmeans 值的順序是隨機的。較大的背景圓圈顯示目標名稱,較小的圓圈很好地分組到它們的質心,來自 kmeans。
from sklearn.datasets import load_iris
iris_data = load_iris()
x = iris_data.data[:, :2]
color_givens = ['magenta', 'gold', 'cyan']
for val, (name, color) in enumerate(zip(iris_data.target_names, color_givens)):
plt.scatter(x[iris_data.target == val, 0], x[iris_data.target == val, 1],
color=color, s=150, alpha=0.6, label=f'given {name}')
k = 3
points, centroids = kmeans(x, k)
colors_kmeans = plt.cm.Set1.colors
for val, color in zip(range(k), colors_kmeans):
plt.scatter(centroids[val, 0], centroids[val, 1], facecolor='none', edgecolor=color, lw=3,
s=150, label=f'centroid {val}')
for val, color in zip(range(k), colors_kmeans):
plt.scatter(x[points == val, 0], x[points == val, 1], color=color, label=f'set {val}')
plt.xlabel(iris_data.feature_names[0])
plt.ylabel(iris_data.feature_names[1])
plt.legend(ncol=3)
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/386435.html
標籤:Python matplotlib scipy jupyter-笔记本
