寶可夢目擊:階層式叢集
我們要延續上一題對傳說寶可夢目擊事件的調查。還記得你在上一題的散佈圖中,找出了兩個目擊特別密集的區域嗎?這代表資料點似乎可分成兩個叢集。這一題中,你會用階層式叢集把這些目擊事件分成兩群。
'x' 與 'y' 是記錄目擊地點 X、Y 座標的欄位,存放在 pandas DataFrame df 中。你可以使用下列工具:matplotlib.pyplot 作為 plt、seaborn 作為 sns,以及 pandas 作為 pd。
本練習屬於課程
Python 中的叢集分析
練習說明
- 匯入
linkage與fcluster函式庫。 - 使用
linkage()搭配 ward 方法計算距離。 - 使用
fcluster(),在兩個叢集的設定下,為每個資料點產生叢集標籤。 - 用 seaborn 繪製散佈圖,並為不同叢集指派不同顏色。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import linkage and fcluster functions
from scipy.cluster.hierarchy import ____, ____
# Use the linkage() function to compute distance
Z = ____(____, 'ward')
# Generate cluster labels
df['cluster_labels'] = ____(____, ____, criterion='maxclust')
# Plot the points with seaborn
sns.scatterplot(x=____, y=____, hue=____, data=df)
plt.show()