【人工智能】机器学习之运用特征脸(eigenface)和sklearn.svm.SVC进行人脸识别

简介: 运用特征脸(eigenface)和sklearn.svm.SVC进行人脸识别。首先需要下载一个经过预处理的数据集,从数据集中找出最有代表性的前5人的预期结果

运用特征脸(eigenface)和sklearn.svm.SVC进行人脸识别。

首先需要下载一个经过预处理的数据集,从数据集中找出最有代表性的前5人的预期结果

第一步,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))
    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()

完整代码:

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

运行结果:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

目录
相关文章
|
2月前
|
数据可视化 Rust 机器学习/深度学习
mlop.ai 无脑使用教程 (机器学习工具 WandB/ClearML 的首个国区开源平替)
mlop.ai 是首个为国区用户优化的机器学习工具,全栈免费开源,是主流付费解决方案 ClearML/WandB 的开源平替。常规实验追踪的工具经常大幅人为降速,mlop因为底层为Rust代码,能轻松支持高频数据写入。如需更多开发者帮助或企业支持,敬请联系cn@mlop.ai
130 12
mlop.ai 无脑使用教程 (机器学习工具 WandB/ClearML 的首个国区开源平替)
|
2月前
|
机器学习/深度学习 人工智能 供应链
从概念到商业价值:AI、机器学习与深度学习全景指南
在这个科技飞速发展的时代🚀,人工智能正以惊人的速度渗透到我们的生活和工作中👀。但面对铺天盖地的AI术语和概念,很多人感到困惑不已😣。"AI"、"机器学习"、"深度学习"和"神经网络"到底有什么区别?它们如何相互关联?如何利用这些技术提升工作效率和创造价值?
85 0
|
4月前
|
机器学习/深度学习 人工智能 自然语言处理
AI训练师入行指南(三):机器学习算法和模型架构选择
从淘金到雕琢,将原始数据炼成智能珠宝!本文带您走进数字珠宝工坊,用算法工具打磨数据金砂。从基础的经典算法到精密的深度学习模型,结合电商、医疗、金融等场景实战,手把手教您选择合适工具,打造价值连城的智能应用。掌握AutoML改装套件与模型蒸馏术,让复杂问题迎刃而解。握紧算法刻刀,为数字世界雕刻文明!
144 6
|
5月前
|
机器学习/深度学习 人工智能 自然语言处理
Java+机器学习基础:打造AI学习基础
随着人工智能(AI)技术的飞速发展,越来越多的开发者开始探索如何将AI技术应用到实际业务场景中。Java作为一种强大的编程语言,不仅在企业级应用开发中占据重要地位,在AI领域也展现出了巨大的潜力。本文将通过模拟一个AI应用,从背景历史、业务场景、优缺点、底层原理等方面,介绍如何使用Java结合机器学习技术来打造一个AI学习的基础Demo。
217 18
|
5月前
|
机器学习/深度学习 算法 数据安全/隐私保护
基于机器学习的人脸识别算法matlab仿真,对比GRNN,PNN,DNN以及BP四种网络
本项目展示了人脸识别算法的运行效果(无水印),基于MATLAB2022A开发。核心程序包含详细中文注释及操作视频。理论部分介绍了广义回归神经网络(GRNN)、概率神经网络(PNN)、深度神经网络(DNN)和反向传播(BP)神经网络在人脸识别中的应用,涵盖各算法的结构特点与性能比较。
|
5月前
|
机器学习/深度学习 数据采集 人工智能
容器化机器学习流水线:构建可复用的AI工作流
本文介绍了如何构建容器化的机器学习流水线,以提高AI模型开发和部署的效率与可重复性。首先,我们探讨了机器学习流水线的概念及其优势,包括自动化任务、确保一致性、简化协作和实现CI/CD。接着,详细说明了使用Kubeflow Pipelines在Kubernetes上构建流水线的步骤,涵盖安装、定义流水线、构建组件镜像及上传运行。容器化流水线不仅提升了环境一致性和可移植性,还通过资源隔离和扩展性支持更大规模的数据处理。
|
7月前
|
机器学习/深度学习 传感器 人工智能
人工智能与机器学习:改变未来的力量####
【10月更文挑战第21天】 在本文中,我们将深入探讨人工智能(AI)和机器学习(ML)的基本概念、发展历程及其在未来可能带来的革命性变化。通过分析当前最前沿的技术和应用案例,揭示AI和ML如何正在重塑各行各业,并展望它们在未来十年的潜在影响。 ####
187 27
|
7月前
|
机器学习/深度学习 人工智能 算法
人工智能浪潮下的编程实践:构建你的第一个机器学习模型
在人工智能的巨浪中,每个人都有机会成为弄潮儿。本文将带你一探究竟,从零基础开始,用最易懂的语言和步骤,教你如何构建属于自己的第一个机器学习模型。不需要复杂的数学公式,也不必担心编程难题,只需跟随我们的步伐,一起探索这个充满魔力的AI世界。
141 12
|
7月前
|
机器学习/深度学习 人工智能 算法
探索人工智能与机器学习的融合之路
在本文中,我们将探讨人工智能(AI)与机器学习(ML)之间的紧密联系以及它们如何共同推动技术革新。我们将深入分析这两种技术的基本概念、发展历程和当前的应用趋势,同时讨论它们面临的挑战和未来的发展方向。通过具体案例研究,我们旨在揭示AI与ML结合的强大潜力,以及这种结合如何为各行各业带来革命性的变化。
150 0
|
8月前
|
机器学习/深度学习 人工智能 自动驾驶
揭秘AI:机器学习如何改变我们的世界
在这篇文章中,我们将深入探讨机器学习如何改变我们的世界。从自动驾驶汽车到智能医疗诊断,机器学习正在逐步渗透到我们生活的每一个角落。我们将通过实例和代码示例,揭示机器学习的工作原理,以及它如何影响我们的生活。无论你是科技爱好者,还是对人工智能充满好奇的普通读者,这篇文章都将为你打开一扇新的大门,带你走进机器学习的世界。
105 0

热门文章

最新文章