# sklearn调包侠之PCA降维

### PCA

PCA（主成分分析），它是一种维度约减算法，即把高维度数据在损失最小的情况下转换为低纬度数据的算法。

### 实战——人脸识别

##### 数据导入

%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

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)

##### 训练模型

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


+ 订阅