评估聚类

Python 中的无监督学习

Benjamin Wilson

Director of Research at lateral.io

评估聚类

  • 可检查与(如)鸢尾花物种的一致性
  • …但若没有物种可对照怎么办?
  • 需要度量聚类质量
  • 帮助选择要寻找的簇数
Python 中的无监督学习

鸢尾花:簇 vs 物种

  • k-means 在鸢尾花样本中找到了 3 个簇
  • 这些簇与物种对应吗?
species  setosa  versicolor  virginica
labels
0             0           2         36
1            50           0          0
2             0          48         14
Python 中的无监督学习

用 pandas 做交叉列联

  • 簇 vs 物种是一次"交叉列联表"
  • 使用 pandas
  • 给定每个样本的物种列表 species
print(species)
['setosa', 'setosa', 'versicolor', 'virginica', ... ]
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
...
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

若没有物种信息,该如何评估聚类?

Python 中的无监督学习

衡量聚类质量

  • 仅用样本及其聚类标签

  • 好的聚类应当紧凑

  • 每个簇内样本应聚得更近

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
Python 中的无监督学习

簇的数量

  • 对 iris 数据集用不同簇数聚类
  • 簇数越多,inertia 越低
  • 最佳簇数是多少?

簇数与 inertia 的折线图

Python 中的无监督学习

应选多少个簇?

  • 好的聚类应当紧凑(即 inertia 低)
  • …但簇不能太多!
  • 在 inertia 曲线中选"肘部"
  • 即 inertia 开始缓慢下降处
  • 如 iris 数据集,3 是不错的选择

簇数与 inertia 的折线图

Python 中的无监督学习

Let's practice!

Python 中的无监督学习

Preparing Video For Download...