用特徵臉及SVM進行人臉辨識實例
本範例所使用的資料庫主要採集於LFW人臉資料庫
採取資料集中最具有代表性的人做預測,以下為預測結果:

(一)引入函式庫

引入函式庫如下: 1. time:計算時間 2. logging:具有除錯功能 3. matplotlib.pyplot:用來繪製影像 4. sklearn.model_selection import train_test_split:將資料集隨機分配成訓練集和測試集 5. sklearn.model_selection import GridSearchCV:搜索指定參數的估計值 6. sklearn.datasets import fetch_lfw_people:載入LFW人臉資料庫 7. sklearn.metrics import classification_report:建立文字報告,顯示主要的分類矩陣 8. sklearn.metrics import confusion_matrix:計算混淆矩陣以評估分類的準確性 9. sklearn.decomposition import PCA:進行主成分分析 10. sklearn.svm import SVC:載入用於分類的向量支持模型

(二)載入LFW人臉資料庫

將資料以numpy array形式存進lfw_people中, 其中min_faces_per_person=70指提取的數據集將僅保留具有至少70個不同圖片的人的圖片。
1
# 下載資料(如果並未下載於電腦中)
2
3
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
Copied!
此範例中共有1288張影像,每張影像大小為62 x 47像素
1
# 查詢影像的大小(為了畫圖)
2
n_samples, h, w = lfw_people.images.shape
3
4
# 為了機器學習,我們直接使用這兩個資料(這個模型忽略了相對像素的位置信息)
5
X = lfw_people.data
6
n_features = X.shape[1]
7
8
# 要預測的標籤是該人的ID
9
y = lfw_people.target
10
target_names = lfw_people.target_names
11
n_classes = target_names.shape[0]
12
13
print("Total dataset size:")
14
print("n_samples: %d" % n_samples)
15
print("n_features: %d" % n_features)
16
print("n_classes: %d" % n_classes)
Copied!
將資料集隨機分配成訓練集和測試集
1
# 分成訓練集和測試集
2
X_train, X_test, y_train, y_test = train_test_split(
3
X, y, test_size=0.25, random_state=42)
Copied!

(三)對於人臉資料計算PCA

計算人臉資料集中的PCA(特徵臉),視為未標籤的資料:使用非監督式提取降維。
1
pca = PCA(n_components=n_components, svd_solver='randomized',
2
whiten=True).fit(X_train)
Copied!
    svd_solver='randomized':用Halko方法運行隨機SVD
    whiten=True:將components向量乘以n_samples的平方根並除以奇異值,以確保具有不相關的輸出。
1
n_components = 150
2
print("Extracting the top %d eigenfaces from %d faces"
3
% (n_components, X_train.shape[0]))
4
t0 = time() #計時
5
pca = PCA(n_components=n_components, svd_solver='randomized',
6
whiten=True).fit(X_train)
7
print("done in %0.3fs" % (time() - t0))
8
9
eigenfaces = pca.components_.reshape((n_components, h, w))
10
11
print("Projecting the input data on the eigenfaces orthonormal basis")
12
t0 = time()
13
#進行降維
14
X_train_pca = pca.transform(X_train)
15
X_test_pca = pca.transform(X_test)
16
print("done in %0.3fs" % (time() - t0))
Copied!

(四)訓練SVM分類模型

SVM模型有兩個非常重要的參數C與gamma。 C:懲罰係數,即對誤差的寬容度。c越高,說明越不能容忍出現誤差,容易過擬合。 gamma:選擇RBF函數作為kernel後,該函數自帶的一個參數。隱含地決定了數據映射到新的特徵空間後的分佈。
1
print("Fitting the classifier to the training set")
2
t0 = time()
3
param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],
4
'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }
5
clf = GridSearchCV(
6
SVC(kernel='rbf', class_weight='balanced'), param_grid
7
)
Copied!
    skernel='rbf':使用(高斯)徑向基函數
    1
    ```python
    2
    clf = clf.fit(X_train_pca, y_train)
    3
    print("done in %0.3fs" % (time() - t0))
    4
    print("Best estimator found by grid search:")
    5
    print(clf.best_estimator_)
    Copied!
    (五)對測試集中進行預測
使用y_pred = clf.predict(X_test_pca),對測試集進行預測。
1
print("Predicting people's names on the test set")
2
t0 = time()
3
#用最佳發現的參數對評估器進行預測。
4
y_pred = clf.predict(X_test_pca)
5
print("done in %0.3fs" % (time() - t0))
6
7
print(classification_report(y_test, y_pred, target_names=target_names))
8
print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))
Copied!

(六)使用matplotlib對預測進行評估

1
def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
2
"""為了畫出人像的函數"""
3
plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))
4
plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
5
for i in range(n_row * n_col):
6
plt.subplot(n_row, n_col, i + 1)
7
plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
8
plt.title(titles[i], size=12)
9
plt.xticks(())
10
plt.yticks(())
11
12
13
# 在部分測試集中繪製預測結果
14
def title(y_pred, y_test, target_names, i):
15
pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]
16
true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]
17
return 'predicted: %s\ntrue: %s' % (pred_name, true_name)
18
19
prediction_titles = [title(y_pred, y_test, target_names, i)
20
for i in range(y_pred.shape[0])]
21
22
plot_gallery(X_test, prediction_titles, h, w)
23
24
# 繪製最有意義的特徵臉
25
eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
26
plot_gallery(eigenfaces, eigenface_titles, h, w)
27
28
plt.show()
Copied!

Total Output:

(七)完整程式碼

Python source code:plot_face_recognition.py
1
from time import time
2
import logging
3
import matplotlib.pyplot as plt
4
5
from sklearn.model_selection import train_test_split
6
from sklearn.model_selection import GridSearchCV
7
from sklearn.datasets import fetch_lfw_people
8
from sklearn.metrics import classification_report
9
from sklearn.metrics import confusion_matrix
10
from sklearn.decomposition import PCA
11
from sklearn.svm import SVC
12
13
14
15
16
print(__doc__)
17
18
# Display progress logs on stdout
19
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
20
21
22
# #############################################################################
23
# Download the data, if not already on disk and load it as numpy arrays
24
25
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
26
27
# introspect the images arrays to find the shapes (for plotting)
28
n_samples, h, w = lfw_people.images.shape
29
30
# for machine learning we use the 2 data directly (as relative pixel
31
# positions info is ignored by this model)
32
X = lfw_people.data
33
n_features = X.shape[1]
34
35
# the label to predict is the id of the person
36
y = lfw_people.target
37
target_names = lfw_people.target_names
38
n_classes = target_names.shape[0]
39
40
print("Total dataset size:")
41
print("n_samples: %d" % n_samples)
42
print("n_features: %d" % n_features)
43
print("n_classes: %d" % n_classes)
44
45
46
# #############################################################################
47
# Split into a training set and a test set using a stratified k fold
48
49
# split into a training and testing set
50
X_train, X_test, y_train, y_test = train_test_split(
51
X, y, test_size=0.25, random_state=42)
52
53
54
# #############################################################################
55
# Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled
56
# dataset): unsupervised feature extraction / dimensionality reduction
57
n_components = 150
58
59
print("Extracting the top %d eigenfaces from %d faces"
60
% (n_components, X_train.shape[0]))
61
t0 = time()
62
pca = PCA(n_components=n_components, svd_solver='randomized',
63
whiten=True).fit(X_train)
64
print("done in %0.3fs" % (time() - t0))
65
66
eigenfaces = pca.components_.reshape((n_components, h, w))
67
68
print("Projecting the input data on the eigenfaces orthonormal basis")
69
t0 = time()
70
X_train_pca = pca.transform(X_train)
71
X_test_pca = pca.transform(X_test)
72
print("done in %0.3fs" % (time() - t0))
73
74
75
# #############################################################################
76
# Train a SVM classification model
77
78
print("Fitting the classifier to the training set")
79
t0 = time()
80
param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],
81
'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }
82
clf = GridSearchCV(
83
SVC(kernel='rbf', class_weight='balanced'), param_grid
84
)
85
clf = clf.fit(X_train_pca, y_train)
86
print("done in %0.3fs" % (time() - t0))
87
print("Best estimator found by grid search:")
88
print(clf.best_estimator_)
89
90
91
# #############################################################################
92
# Quantitative evaluation of the model quality on the test set
93
94
print("Predicting people's names on the test set")
95
t0 = time()
96
y_pred = clf.predict(X_test_pca)
97
print("done in %0.3fs" % (time() - t0))
98
99
print(classification_report(y_test, y_pred, target_names=target_names))
100
print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))
101
102
103
# #############################################################################
104
# Qualitative evaluation of the predictions using matplotlib
105
106
def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
107
"""Helper function to plot a gallery of portraits"""
108
plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))
109
plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
110
for i in range(n_row * n_col):
111
plt.subplot(n_row, n_col, i + 1)
112
plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
113
plt.title(titles[i], size=12)
114
plt.xticks(())
115
plt.yticks(())
116
117
118
# plot the result of the prediction on a portion of the test set
119
120
def title(y_pred, y_test, target_names, i):
121
pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]
122
true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]
123
return 'predicted: %s\ntrue: %s' % (pred_name, true_name)
124
125
prediction_titles = [title(y_pred, y_test, target_names, i)
126
for i in range(y_pred.shape[0])]
127
128
plot_gallery(X_test, prediction_titles, h, w)
129
130
# plot the gallery of the most significative eigenfaces
131
132
eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
133
plot_gallery(eigenfaces, eigenface_titles, h, w)
134
135
plt.show()
Copied!
Last modified 1yr ago