无监督学习

Python 中的无监督学习

Benjamin Wilson

Director of Research at lateral.io

无监督学习

  • 无监督学习在数据中发现模式
  • 例如:按购买记录对客户进行"聚类"
  • 利用购买模式压缩数据("降维")
Python 中的无监督学习

监督学习 vs 无监督学习

  • 监督学习为预测任务找出模式
  • 例如:将肿瘤分类为良性或恶性("标签")
  • 无监督学习在数据中找出模式
  • ……但不针对特定预测任务
Python 中的无监督学习

鸢尾花数据集

  • 多株鸢尾花的测量数据
  • 三个物种:
    • setosa
    • versicolor
    • virginica
  • 花瓣长、花瓣宽、萼片长、萼片宽(数据集的"特征")

鸢尾花

1 https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html
Python 中的无监督学习

数组、特征与样本

  • 2D NumPy 数组
  • 列是测量值(特征)
  • 行表示鸢尾花(样本)
Python 中的无监督学习

鸢尾花数据是4维的

  • 鸢尾花样本是4维空间中的点
  • 维度 = 特征数
  • 维度过高,无法可视化!
  • ……但无监督学习能提供洞见
Python 中的无监督学习

k-means 聚类

  • 发现样本的聚类
  • 需指定聚类数量
  • sklearn(scikit-learn)中实现
Python 中的无监督学习
print(samples)
[[ 5.   3.3  1.4  0.2]
 [ 5.   3.5  1.3  0.3]
 ...
 [ 7.2  3.2  6.   1.8]]
from sklearn.cluster import KMeans

model = KMeans(n_clusters=3)
model.fit(samples)
KMeans(n_clusters=3)
labels = model.predict(samples)

print(labels)
[0 0 1 1 0 1 2 1 0 1 ...]
Python 中的无监督学习

新样本的聚类标签

  • 新样本可分配到现有聚类
  • k-means 记住每个聚类的均值("质心")
  • 为每个新样本找到最近的质心
Python 中的无监督学习

新样本的聚类标签

print(new_samples)
[[ 5.7  4.4  1.5  0.4]
 [ 6.5  3.   5.5  1.8]
 [ 5.8  2.7  5.1  1.9]]
new_labels = model.predict(new_samples)

print(new_labels)
[0 2 1]
Python 中的无监督学习

散点图

  • 萼片长度 vs 花瓣长度的散点图
  • 每个点代表一个鸢尾花样本
  • 用聚类标签着色
  • PyPlot(matplotlib.pyplot

散点图

Python 中的无监督学习

散点图

import matplotlib.pyplot as plt

xs = samples[:,0] ys = samples[:,2]
plt.scatter(xs, ys, c=labels)
plt.show()
Python 中的无监督学习

让我们来练习!

Python 中的无监督学习

Preparing Video For Download...