pca人脸识别python_[机器学习] 用PCA进行人脸识别

本文通过Python演示PCA在人脸识别中的应用,详细解析代码流程,包括数据划分、PCA降维、SVM分类,并展示了实验结果。PCA用于将原始高维特征降至150维,提高计算效率,最终实现不错的人脸识别准确率。
摘要由CSDN通过智能技术生成

本文会带你详细的分析PCA人脸识别的代码

PCA在人脸识别中有重要的应用,如果想详细了解PCA的原理,可以看我的这篇文章:任妍Carol:[机器学习] 人脸识别的重要方法——PCA​zhuanlan.zhihu.com

人脸识别的原代码来自于Sklearn,可以通过这个链接访问:Faces recognition example using eigenfaces and SVMs​scikit-learn.org

这个人脸识别的项目采集了7个知名人物的面部图片,共有1288张照片,每张图片的特征有1850,非常庞大,但是利用PCA,可以把这样庞大的特征复合为150个,进而进行分析

最后的准确率也是不错的哟

一起来开始这个项目吧~

下载图片

下载代码

如果你用Python,就下载第一个文件,如果用Jupter,就下载第二个

然后直接运行这个代码就可以看到结果啦

如果遇到某些模块没有下载而出现的bug,可以参考[机器学习] 项目准备工作文章

然后我们一起来看看这个代码和结果

代码分析

我们来一段一段的分析这个代码:

# 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)

这段代码的作用是:

1. 将数据分成训练集和测试集,其中25%为测试集

# Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled

# dataset): unsupervised feature extraction / dimensionality reduction

n_components = 150

print("Extracting the top%deigenfaces from%dfaces"

% (n_components, X_train.shape[0]))

t0 = time()

pca = PCA(n_components=n_components, svd_solver='randomized',

whiten=True).fit(X_train)

print("done in%0.3fs" % (time() - t0))

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

print("Projecting the input data on the eigenfaces orthonormal basis")

t0 = time()

X_train_pca = pca.transform(X_train)

X_test_pca = pca.transform(X_test)

print("done in%0.3fs" % (time() - t0))

这段就是PCA发挥作用了

1. 将PCA的主成分设为150个 2. 创建一个pca,进行训练 3. 得到特征脸(就是用我们的特征向量重新排布,就像一张脸一样) 4. 对x训练集和测试集进行pca转换

这里涉及到的一些知识可以再给大家重新讲一下PCA背后的数学原理,感兴趣的同学可以搜搜博客详细了解(可以参考PCA的数学原理,我这里只给出一个大略的解释(需要你有很强的代数和概率的知识)。

比放说在进行人脸识别的时候,我们有200张图,每张图1800个像素点,那么每个像素点都是一个特征,按理说都需要进行分析的,但是对这个1800×200的矩阵进行计算实在是太麻烦

于是我们希望将它降维处理,比方说150×200,PCA要做的就是找到这1800个特征的协方差矩阵,因为协方差矩阵是一个很棒的矩阵,它的主对角线就是每个特征的方差,而其余部分就是每个特征和别的特征之间的协方差

主对角线的数据很有意义,因为前面提到我们要找的新的坐标轴的方向就是使方差最大的方向

其余部分也很有意义,因为协方差体现两个不同的变量之间的相关关系,当协方差为0时,表示这个变量和其他变量之间都没有关系啦

协方差矩阵还有一点非常好的就是它竟然是一个实对称矩阵哦,实对称矩阵永远都可以表示为一个对角矩阵和正交矩阵的乘积

这个正交矩阵可以看作是新的坐标系,而对角矩阵刻画了方差,我们只要挑选方差最大的那150个就可以了,同样对应那150维的坐标系,剩下的方差太小,没有价值可以舍去

然后

# Train a SVM classification model

print("Fitting the classifier to the training set")

t0 = time()

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, cv=5)

clf = clf.fit(X_train_pca, y_train)

print("done in%0.3fs" % (time() - t0))

print("Best estimator found by grid search:")

print(clf.best_estimator_)

1. 创建支持向量机的分类器clf 2. 用我们之前经过PCA处理的X训练集和Y训练集进行分类

然后就是预测

# Quantitative evaluation of the model quality on the test set

print("Predicting people's names on the test set")

t0 = time()

y_pred = clf.predict(X_test_pca)

print("done in%0.3fs" % (time() - t0))

print(classification_report(y_test, y_pred, target_names=target_names))

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

1. 对测试集进行预测

最后就是绘图

# 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))

plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)

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()

如果你觉得写的很好不要吝惜赞哦

更多内容请看本专栏目录任妍Carol:机器学习小白笔记目录​zhuanlan.zhihu.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值