開始使用免費開始

穀物有幾個叢集?

在影片中,你學到如何利用 k-means 的慣性(inertia)圖來為資料集選擇合適的叢集數。這裡提供了一個陣列 samples,包含穀物樣本的量測值(例如面積、周長、長度等)。在這個例子中,幾個叢集比較合適?

KMeans 和 PyPlot(plt)已為你匯入。

本資料集來自 UCI Machine Learning Repository

本練習屬於課程

Unsupervised Learning in Python

檢視課程

練習說明

  • 對於給定的每個 k 值,依序完成以下步驟:
  • 建立一個具有 k 個叢集、名為 modelKMeans 實例。
  • 將模型擬合到穀物資料 samples
  • 取出 modelinertia_ 屬性值,並將其附加到清單 inertias
  • 繪製 ksinertias 的程式碼已經為你寫好,按下送出即可看到圖表!

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

ks = range(1, 6)
inertias = []

for k in ks:
    # Create a KMeans instance with k clusters: model
    ____
    
    # Fit model to samples
    ____
    
    # Append the inertia to the list of inertias
    ____
    
# Plot ks vs inertias
plt.plot(ks, inertias, '-o')
plt.xlabel('number of clusters, k')
plt.ylabel('inertia')
plt.xticks(ks)
plt.show()
編輯並執行程式碼