一致的分群樣式
既然你已經熟悉隨機種子(seed)的影響,接著我們來看看 k-means 分群傾向產生一致大小分群的偏誤。
在這個練習中,我們要使用一個「像老鼠」的資料集。所謂像老鼠的資料集,是指一組點狀資料排成像老鼠頭的樣子:共有 3 個圓形排列的群集,分別對應臉和兩隻耳朵。
以下是典型的「像老鼠」資料集範例(來源)。
資料儲存在 pandas 的 DataFrame mouse 中。x_scaled 和 y_scaled 是資料點標準化後的 X 與 Y 座標欄位名稱。
本練習屬於課程
Python 中的叢集分析
練習說明
- 在 SciPy 中匯入
kmeans和vq函式。 - 使用
kmeans()函式並設定 3 個群集,產生群中心。 - 使用上一步產生的群中心搭配
vq()建立群集標籤。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the kmeans and vq functions
____
# Generate cluster centers
cluster_centers, distortion = ____
# Assign cluster labels
mouse['cluster_labels'], distortion_list = ____
# Plot clusters
sns.scatterplot(x='x_scaled', y='y_scaled',
hue='cluster_labels', data = mouse)
plt.show()