基于支持向量机(svm)的人脸识别

本文介绍了如何使用Python和scikit-learn库从LFW数据集中加载和可视化人脸数据,通过PCA降维和SVC构建人脸识别模型。随后进行了模型训练、参数调优、预测以及性能评估,包括精确率、召回率和F1分数。最终展示了混淆矩阵以可视化模型性能。
摘要由CSDN通过智能技术生成

注意:本文引用自专业人工智能社区Venus AI

更多AI知识请参考原站 ([www.aideeplearning.cn])

数据集加载与可视化

from sklearn.datasets import fetch_lfw_people
faces = fetch_lfw_people(min_faces_per_person=60) 
# Check out sample images
import matplotlib.pyplot as plt
fig, ax = plt.subplots(3, 5)
for i, axi in enumerate(ax.flat):
    axi.imshow(faces.images[i], cmap='bone')
    axi.set(xticks=[], yticks=[], xlabel=faces.target_names[faces.target[i]])

使用 PCA 和 SVC 构建模型

from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
pca = PCA(n_components=150, whiten=True, random_state=42)
svc = SVC(kernel='rbf', class_weight='balanced')

model = make_pipeline(pca, svc)
# train, test
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(faces['data'], faces['target'], test_size=0.2, random_state=42)

使用网格搜索 CV 查找最佳模型

from sklearn.model_selection import GridSearchCV

param_grid ={
    'svc__C': [1, 5, 10, 15],
    'svc__gamma': [0.0001, 0.0005, 0.001, 0.005],
}
grid = GridSearchCV(model, param_grid=param_grid, cv=5)
%time grid.fit(X_train, y_train)

 

{'svc__C': 1, 'svc__gamma': 0.005}
grid.best_params_
grid.best_estimator_

使用最佳模型进行预测 

final_model = grid.best_estimator_
y_pred = final_model.predict(X_test)

 可视化数据

fig, ax = plt.subplots(4, 6)
for i, axi in enumerate(ax.flat):
    axi.imshow(X_test[i].reshape(62, 47), cmap='bone')
    axi.set(xticks=[], yticks=[])
    axi.set_ylabel(faces.target_names[y_pred[i]].split()[-1], 
                  color='black' if y_pred[i] == y_test[i] # correct label
                  else 'red') # incorrect label

fig.suptitle('Predicted Names; Incorrected Labels in Red', size=14);

模型评估指标

from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred, 
                            target_names=faces.target_names))
                   precision    recall  f1-score   support

     Ariel Sharon       0.90      0.75      0.82        12
     Colin Powell       0.72      0.94      0.81        51
  Donald Rumsfeld       0.88      0.88      0.88        25
    George W Bush       0.97      0.88      0.92        98
Gerhard Schroeder       0.88      0.71      0.79        21
      Hugo Chavez       0.85      0.73      0.79        15
Junichiro Koizumi       1.00      1.00      1.00        10
       Tony Blair       0.90      0.92      0.91        38

         accuracy                           0.87       270
        macro avg       0.89      0.85      0.86       270
     weighted avg       0.89      0.87      0.88       270
from sklearn.metrics import confusion_matrix

cm = confusion_matrix(y_test, y_pred)
cm = cm.T

print(cm)
import seaborn as sns
sns.heatmap(data=cm, 
            square=True, 
            annot=True, 
            cbar=False,
            xticklabels=faces.target_names,
            yticklabels=faces.target_names
           );

plt.xlabel('True Labels')
plt.ylabel('Predicted Labels');

项目资源下载

详情请见基于支持向量机(SVM)的人脸识别-VenusAI (aideeplearning.cn) 

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值