Elbow method
在前一個練習中,你已經實作了 8 個群集的 MiniBatch K-means,但並沒有實際檢查正確的群集數應該是多少。對於我們第一個詐欺偵測的方法來說,正確設定群集數量 很重要,特別是當你要把那些群集的離群點當作詐欺預測時。為了決定要用多少個群集,我們來套用 Elbow method,看看依據這個方法,最佳的群集數應該是多少。
X_scaled 依然可供你使用,且已經從 sklearn 匯入了 MiniBatchKMeans。
本練習屬於課程
Fraud Detection in Python
練習說明
- 將範圍設定為 1 到 5 個群集。
- 使用列表生成式,對範圍內所有群集數執行 MiniBatch K-means。
- 針對標準化後的資料擬合每個模型,並從同一份標準化資料取得分數。
- 繪製群集數與其對應分數的圖形,執行需要數秒。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define the range of clusters to try
clustno = range(____, ____)
# Run MiniBatch Kmeans over the number of clusters
kmeans = [____(n_clusters=i, random_state=0) for ____ in ____]
# Obtain the score for each model
score = [kmeans[i].fit(____).score(____) for i in range(len(kmeans))]
# Plot the models and their respective score
plt.plot(____, ____)
plt.xlabel('Number of Clusters')
plt.ylabel('Score')
plt.title('Elbow Curve')
plt.show()