# 运用特征脸（eigenface）和sklearn.svm.SVC进行人脸识别。

## 第一步，import导入实验所用到的包

import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import fetch_lfw_people
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import PCA
from sklearn.svm import SVC

## 第二步，下载人脸数据

lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)

“Labeled Faces in the Wild”
http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz

## 第三步，特征提取


X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42)

n_components = 150

pca = PCA(n_components=n_components, svd_solver='randomized',
whiten=True).fit(X_train)

eigenfaces = pca.components_.reshape((n_components, h, w))

X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)

## 第四步，建立SVM分类模型


param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],
'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }
clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)
clf = clf.fit(X_train_pca, y_train)
print("Best estimator found by grid search:")
print(clf.best_estimator_)

## 第五步， 模型评估


y_pred = clf.predict(X_test_pca)

print(classification_report(y_test, y_pred, target_names=target_names))
print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))

## 第六步，预测结果可视化

# 预测结果可视化
def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
"""Helper function to plot a gallery of portraits"""
plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))
for i in range(n_row * n_col):
plt.subplot(n_row, n_col, i + 1)
plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
plt.title(titles[i], size=12)
plt.xticks(())
plt.yticks(())

# plot the result of the prediction on a portion of the test set
def title(y_pred, y_test, target_names, i):
pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]
true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]
return 'predicted: %s\ntrue:      %s' % (pred_name, true_name)

prediction_titles = [title(y_pred, y_test, target_names, i)
for i in range(y_pred.shape[0])]
plot_gallery(X_test, prediction_titles, h, w)

# plot the gallery of the most significative eigenfaces
eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
plot_gallery(eigenfaces, eigenface_titles, h, w)
plt.show()

## 完整代码：

# import导入实验所用到的包
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import fetch_lfw_people
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import PCA
from sklearn.svm import SVC
# 下载人脸数据
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)

# introspect the images arrays to find the shapes (for plotting)
n_samples, h, w = lfw_people.images.shape

# for machine learning we use the 2 data directly (as relative pixel
# positions info is ignored by this model)
X = lfw_people.data
n_features = X.shape[1]

# the label to predict is the id of the person
y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0]

# Split into a training set and a test set using a stratified k fold
# split into a training and testing set
# 特征提取
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42)

# Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled
# dataset): unsupervised feature extraction / dimensionality reduction
n_components = 150

pca = PCA(n_components=n_components, svd_solver='randomized',
whiten=True).fit(X_train)

eigenfaces = pca.components_.reshape((n_components, h, w))

X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)

# Train a SVM classification model
# 建立SVM分类模型
param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],
'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }
clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)
clf = clf.fit(X_train_pca, y_train)
print("Best estimator found by grid search:")
print(clf.best_estimator_)

# Quantitative evaluation of the model quality on the test set
# 模型评估
y_pred = clf.predict(X_test_pca)

print(classification_report(y_test, y_pred, target_names=target_names))
print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))

# Qualitative evaluation of the predictions using matplotlib
# 预测结果可视化
def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
"""Helper function to plot a gallery of portraits"""
plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))
for i in range(n_row * n_col):
plt.subplot(n_row, n_col, i + 1)
plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
plt.title(titles[i], size=12)
plt.xticks(())
plt.yticks(())

# plot the result of the prediction on a portion of the test set
def title(y_pred, y_test, target_names, i):
pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]
true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]
return 'predicted: %s\ntrue:      %s' % (pred_name, true_name)

prediction_titles = [title(y_pred, y_test, target_names, i)
for i in range(y_pred.shape[0])]
plot_gallery(X_test, prediction_titles, h, w)

# plot the gallery of the most significative eigenfaces
eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
plot_gallery(eigenfaces, eigenface_titles, h, w)
plt.show()


## 运行结果：

|
1月前
|

128 1
|
10天前
|

【8月更文挑战第4天】 在本文中，我们将深入探讨机器学习，这是人工智能的一个关键分支。我们将了解其基本概念，主要类型以及一些应用实例。我们还将讨论一些挑战和未来的趋势。无论你是初学者还是有经验的程序员，这篇文章都将为你提供有价值的信息。
24 7
|
11天前
|

23 3
|
6天前
|

【8月更文挑战第8天】 随着科技的不断进步，人工智能（AI）和机器学习已经从科幻小说的概念变成了我们日常生活的一部分。本文将探讨AI和机器学习如何相互作用，共同推动技术发展的边界，并讨论这些技术如何影响我们的工作、生活和社会结构。通过分析最新的研究和应用实例，我们将了解这一领域的创新动态及其对未来的深远影响。
14 1
|
16天前
|

【7月更文挑战第29天】随着科技的不断进步，人工智能领域正迎来前所未有的发展机遇。本文将深入探讨机器学习与深度学习这两大技术支柱如何相互促进，共同推动人工智能向更高层次发展。通过分析当前的研究趋势和技术挑战，我们将描绘出一个更加智能、互联的未来图景。
26 3
|
20天前
|

15 1
|
1天前
|

|
1月前
|

AIGC人工智能生成内容之机器学习
7月更文挑战第1天
31 3
|
14天前
|

31 0
|
14天前
|

ERP系统中的人工智能与机器学习应用：提升企业智能化管理
【7月更文挑战第29天】 ERP系统中的人工智能与机器学习应用：提升企业智能化管理
51 0