評估分群

Unsupervised Learning in Python

Benjamin Wilson

Director of Research at lateral.io

評估分群

  • 可與例如 iris 物種比對
  • 但若沒有物種可對照呢?
  • 衡量分群品質
  • 協助決定要找幾個群
Unsupervised Learning in Python

Iris:群與物種對照

  • k-means 在 iris 樣本中找到 3 個群
  • 這些群是否對應到物種?
species  setosa  versicolor  virginica
labels
0             0           2         36
1            50           0          0
2             0          48         14
Unsupervised Learning in Python

用 pandas 做交叉列聯

  • 群與物種的對照是「交叉列聯表」
  • 使用 pandas 函式庫
  • 已有每個樣本的物種清單 species
print(species)
['setosa', 'setosa', 'versicolor', 'virginica', ... ]
Unsupervised Learning in Python

對齊標籤與物種

import pandas as pd
df = pd.DataFrame({'labels': labels, 'species': species})
print(df)
     labels     species
0         1      setosa
1         1      setosa
2         2  versicolor
3         2   virginica
4         1      setosa
...
Unsupervised Learning in Python

標籤與物種的交叉表

ct = pd.crosstab(df['labels'], df['species'])
print(ct)
species  setosa  versicolor  virginica
labels
0             0           2         36
1            50           0          0
2             0          48         14

若沒有物種資訊,要如何評估分群?

Unsupervised Learning in Python

衡量分群品質

  • 只用樣本與其群標籤

  • 好的分群要有緊密群集

  • 每個群內樣本彼此接近

Unsupervised Learning in Python

Inertia 衡量分群品質

  • 衡量群的分散程度(越低越好)
  • 各樣本到其群中心的距離
  • fit() 之後可由屬性 inertia_ 取得
  • k-means 在選群時會最小化 inertia
from sklearn.cluster import KMeans

model = KMeans(n_clusters=3)
model.fit(samples)
print(model.inertia_)
78.9408414261
Unsupervised Learning in Python

群數的選擇

  • 對 iris 資料集用不同群數分群
  • 群越多,inertia 越低
  • 最佳群數是多少?

群數 vs. inertia 的折線圖

Unsupervised Learning in Python

要選幾個群?

  • 好的分群要有緊密群集(inertia 低)
  • 但也不能有太多群!
  • 在 inertia 圖選「手肘」點
  • 也就是下降開始變慢之處
  • 例如 iris 資料集,3 是不錯的選擇

群數 vs. inertia 的折線圖

Unsupervised Learning in Python

一起來練習吧!

Unsupervised Learning in Python

Preparing Video For Download...