以 PCA 進行降維

Unsupervised Learning in Python

Benjamin Wilson

Director of Research at lateral.io

降維

  • 用較少特徵表示同一資料
  • 機器學習流程的重要步驟
  • 可用 PCA 執行
Unsupervised Learning in Python

以 PCA 進行降維

  • PCA 特徵依變異由大到小排序
  • 假設低變異特徵是「雜訊」
  • …而高變異特徵具資訊量

長條圖顯示 PCA 特徵編號對變異,1 與 2 間有垂直線,左箭頭標示 informative、右箭頭標示 noisy

Unsupervised Learning in Python

以 PCA 進行降維

  • 指定要保留的特徵數
  • 例如 PCA(n_components=2)
  • 保留前 2 個 PCA 特徵
  • 內在維度是好選擇
Unsupervised Learning in Python

Iris 資料集的降維

  • samples = iris 量測的陣列(4 個特徵)
  • species = iris 品種編號的列表
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)
Unsupervised Learning in Python

Iris 資料集的 2 維視圖

  • PCA 已將維度降為 2
  • 保留變異最高的 2 個 PCA 特徵
  • 重要資訊仍在:品種仍可區分
import matplotlib.pyplot as plt
xs = transformed[:,0]
ys = transformed[:,1]
plt.scatter(xs, ys, c=species)
plt.show()

對 Iris 資料集做 PCA 的散佈圖

Unsupervised Learning in Python

以 PCA 進行降維

  • 丟棄低變異的 PCA 特徵
  • 假設高變異特徵具有資訊量
  • 此假設常見成立(如 iris)
Unsupervised Learning in Python

字詞頻率陣列

  • 列代表文件,欄代表單字
  • 內容衡量每個文件中各字的出現
  • …以「tf-idf」衡量(稍後介紹)

字詞頻率陣列

Unsupervised Learning in Python

稀疏陣列與 csr_matrix

  • 「稀疏」:多數欄位為 0
  • 可用 scipy.sparse.csr_matrix 取代 NumPy 陣列
  • csr_matrix 只記錄非零值(省空間!)

字詞頻率陣列

Unsupervised Learning in 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)
Unsupervised Learning in Python

一起來練習吧!

Unsupervised Learning in Python

Preparing Video For Download...