計算並繪製平方誤差總和
現在,你要計算叢集數從 1 到 10 時的平方誤差總和。
你會使用上一個練習中建立並正規化過的 RFMT 資料,已存為 datamart_rfmt_normalized。scikit-learn 的 KMeans 模組也已匯入。我們也已初始化一個空的字典 sse = {} 用來儲存平方誤差總和。
可以在主控台自由探索資料。
本練習屬於課程
Python 的客群分群
練習說明
- 以
k個叢集與 random state 設為 1 初始化 KMeans,並在正規化後的資料集上進行擬合。 - 將平方距離總和指定給字典
sse中對應k的元素。 - 加上繪圖標題「The Elbow Method」、X 軸標籤「k」,以及 Y 軸標籤「SSE」。
- 將字典中以鍵儲存的每個
k對應的 SSE 值繪製出來。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Fit KMeans and calculate SSE for each k between 1 and 10
for k in range(1, 11):
# Initialize KMeans with k clusters and fit it
kmeans = ____(____=____, ____=1 ).____(datamart_rfmt_normalized)
# Assign sum of squared distances to k element of the sse dictionary
____[____] = kmeans.____
# Add the plot title, x and y axis labels
plt.____('The Elbow Method')
plt.____('____')
plt.____('____')
# Plot SSE values for each k stored as keys in the dictionary
sns.____(x=list(sse.____()), y=list(sse.____()))
plt.show()