用 PCA 进行降维

Python 中的无监督学习

Benjamin Wilson

Director of Research at lateral.io

降维

  • 用更少的特征表示同一数据
  • 机器学习流水线的重要步骤
  • 可用 PCA 实现
Python 中的无监督学习

用 PCA 进行降维

  • 主成分按方差递减排序
  • 假设低方差成分是"噪声"
  • ……高方差成分更有信息量

柱状图:主成分编号 vs 方差;1 与 2 之间有竖线,左侧箭头标注 informative,右侧箭头标注 noisy

Python 中的无监督学习

用 PCA 进行降维

  • 指定要保留的特征数
  • 例如 PCA(n_components=2)
  • 保留前 2 个主成分
  • 内在维度是好选择
Python 中的无监督学习

鸢尾花数据集的降维

  • samples = 鸢尾花测量数组(4 个特征)
  • species = 鸢尾花物种编号列表
from sklearn.decomposition import PCA

pca = PCA(n_components=2)
pca.fit(samples)
PCA(n_components=2)
transformed = pca.transform(samples)
print(transformed.shape)
(150, 2)
Python 中的无监督学习

二维中的鸢尾花数据集

  • PCA 将维度降到 2
  • 保留方差最高的 2 个主成分
  • 关键信息保留:物种仍可区分
import matplotlib.pyplot as plt
xs = transformed[:,0]
ys = transformed[:,1]
plt.scatter(xs, ys, c=species)
plt.show()

对鸢尾花数据集进行 PCA 的散点图

Python 中的无监督学习

用 PCA 进行降维

  • 丢弃低方差主成分
  • 假设高方差成分更有信息量
  • 该假设在实践中常成立(如鸢尾花)
Python 中的无监督学习

词频数组

  • 行表示文档,列表示词
  • 元素表示词在文档中的出现情况
  • ……可用"tf-idf"度量(稍后介绍)

词频数组

Python 中的无监督学习

稀疏数组与 csr_matrix

  • "稀疏":大多元素为 0
  • 可用 scipy.sparse.csr_matrix 代替 NumPy 数组
  • csr_matrix 只存非零元素(省空间)

词频数组

Python 中的无监督学习

TruncatedSVD 与 csr_matrix

  • scikit-learn 的 PCA 不支持 csr_matrix
  • 请改用 scikit-learn 的 TruncatedSVD
  • 变换效果等同
from sklearn.decomposition import TruncatedSVD
model = TruncatedSVD(n_components=3)
model.fit(documents)  # documents is csr_matrix
transformed = model.transform(documents)
Python 中的无监督学习

Passons à la pratique !

Python 中的无监督学习

Preparing Video For Download...