K-means 分群:第一個練習
這個練習會讓你熟悉如何在資料集上使用 k-means 分群。我們來用 Comic Con 資料集,看看 k-means 分群在其上的運作方式。
回想 k-means 分群的兩個步驟:
- 透過
kmeans()函式定義叢集中心。它有兩個必要引數:觀測值與叢集數量。 - 透過
vq()函式指派叢集標籤。它有兩個必要引數:觀測值與叢集中心。
資料儲存在一個 pandas DataFrame comic_con 中。x_scaled 與 y_scaled 是某一時間點人們的 X 與 Y 座標經標準化後的欄位名稱。
本練習屬於課程
Python 中的叢集分析
練習說明
- 在 SciPy 中匯入
kmeans與vq函式。 - 使用
kmeans()函式並設定叢集數為 2,產生叢集中心。 - 使用這些叢集中心建立叢集標籤。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the kmeans and vq functions
from ____.cluster.vq import ____, ____
# Generate cluster centers
cluster_centers, distortion = ____
# Assign cluster labels
comic_con['cluster_labels'], distortion_list = ____
# Plot clusters
sns.scatterplot(x='x_scaled', y='y_scaled',
hue='cluster_labels', data = comic_con)
plt.show()