PCA
PCA(主成分分析), 它是一种维度约减算法, 即把高维度数据在损失最小的情况下转换为低纬度数据的算法.
实战 -- 人脸识别
数据导入
该数据集可通过 sklearn 进行下载. 数据集总共包含 40 位人员的照片, 每个人 10 张照片. 通过 fetch_olivetti_faces 方法下载的图片, 进行了处理, 人脸会居中, 并裁剪为 64*64 大小.
- %matplotlib inline
- import matplotlib.pyplot as plt
- import numpy as np
- from sklearn.datasets import fetch_olivetti_faces
- faces = fetch_olivetti_faces()
- X = faces.data
- y = faces.target
- pca
由于数据集样本少 (400), 特征高 (64*64), 需要对数据进行降维后, 再建立模型.
那到底选择多少主成分合适了? 我们这里计算多组主成分, 获取数据还原率, 如图所示, 选择 140 个主成分, 可以保证还原率大于 0.95.
- from sklearn.decomposition import PCA
- candidate_components = range(10, 300, 30)
- explained_ratios = []
- for c in candidate_components:
- pca = PCA(n_components=c)
- X_pca = pca.fit_transform(X)
- explained_ratios.append(np.sum(pca.explained_variance_ratio_))
- plt.figure(figsize=(10, 6), dpi=144)
- plt.grid()
- plt.plot(candidate_components, explained_ratios)
- plt.xlabel('Number of PCA Components')
- plt.ylabel('Explained Variance Ratio')
- plt.title('Explained variance ratio for PCA')
- plt.yticks(np.arange(0.5, 1.05, .05))
- plt.xticks(np.arange(0, 300, 20))
切分数据集
- from sklearn.model_selection import train_test_split
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=33)
训练模型
这里使用 svm 进行模型训练, 并使用网格搜索来获取最优参数.
- from sklearn.model_selection import GridSearchCV
- from sklearn.svm import SVC
- param_grid = {'C': [1, 5, 10, 50, 100],
- 'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01]}
- clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)
- clf = clf.fit(X_train_pca, y_train)
- print(clf.best_params_, clf.best_score_)
- # result
- # {'C': 5, 'gamma': 0.005} 0.778125
模型评估
最后, 对模型进行评估:
- clf.best_estimator_.score(X_test_pca, y_test)
- # result
- # 0.96250000000000002
来源: http://www.jianshu.com/p/a53f9d847c0d