【人工智能】机器学习之运用特征脸(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()

运行结果:

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

目录
相关文章
|
机器学习/深度学习 人工智能 监控
人工智能之人脸识别技术应用场景
人脸识别技术是一种通过计算机技术和模式识别算法来识别和验证人脸的技术。它可以用于识别人脸的身份、检测人脸的表情、年龄、性别等特征,以及进行人脸比对和活体检测等应用。
1187 1
|
机器学习/深度学习 存储 设计模式
特征时序化建模:基于特征缓慢变化维度历史追踪的机器学习模型性能优化方法
本文探讨了数据基础设施设计中常见的一个问题:数据仓库或数据湖仓中的表格缺乏构建高性能机器学习模型所需的历史记录,导致模型性能受限。为解决这一问题,文章介绍了缓慢变化维度(SCD)技术,特别是Type II类型的应用。通过SCD,可以有效追踪维度表的历史变更,确保模型训练数据包含完整的时序信息,从而提升预测准确性。文章还从数据工程师、数据科学家和产品经理的不同视角提供了实施建议,强调历史数据追踪对提升模型性能和业务洞察的重要性,并建议采用渐进式策略逐步引入SCD设计模式。
686 8
特征时序化建模:基于特征缓慢变化维度历史追踪的机器学习模型性能优化方法
|
机器学习/深度学习 算法 Python
机器学习特征筛选:向后淘汰法原理与Python实现
向后淘汰法(Backward Elimination)是机器学习中一种重要的特征选择技术,通过系统性地移除对模型贡献较小的特征,以提高模型性能和可解释性。该方法从完整特征集出发,逐步剔除不重要的特征,最终保留最具影响力的变量子集。其优势包括提升模型简洁性和性能,减少过拟合,降低计算复杂度。然而,该方法在高维特征空间中计算成本较高,且可能陷入局部最优解。适用于线性回归、逻辑回归等统计学习模型。
644 7
|
机器学习/深度学习 算法 数据可视化
机器学习模型中特征贡献度分析:预测贡献与错误贡献
本文将探讨特征重要性与特征有效性之间的关系,并引入两个关键概念:预测贡献度和错误贡献度。
1421 4
|
存储 分布式计算 API
基于PAI-FeatureStore的LLM embedding功能,结合通义千问大模型,可通过以下链路实现对物品标题、内容字段的离线和在线特征管理。
本文介绍了基于PAI-FeatureStore和通义千问大模型的LLM embedding功能,实现物品标题、内容字段的离线与在线特征管理。核心内容包括:1) 离线特征生产(MaxCompute批处理),通过API生成Embedding并存储;2) 在线特征同步,实时接入数据并更新Embedding至在线存储;3) Python SDK代码示例解析;4) 关键步骤说明,如客户端初始化、参数配置等;5) 最佳实践,涵盖性能优化、数据一致性及异常处理;6) 应用场景示例,如推荐系统和搜索排序。该方案支持端到端文本特征管理,满足多种语义理解需求。
465 1
|
存储 机器学习/深度学习 缓存
特征平台PAI-FeatureStore的功能列表
本内容介绍了阿里云PAI FeatureStore的功能与使用方法,涵盖离线和在线特征管理、实时特征视图、行为序列特征视图、FeatureStore SDK的多语言支持(如Go、Java、Python)、特征生产简化方案、FeatureDB存储特性(高性能、低成本、及时性)、训练样本导出以及自动化特征工程(如AutoFE)。同时提供了相关文档链接和技术细节,帮助用户高效构建和管理特征工程。适用于推荐系统、模型训练等场景。
642 2
|
机器学习/深度学习 算法 数据安全/隐私保护
基于机器学习的人脸识别算法matlab仿真,对比GRNN,PNN,DNN以及BP四种网络
本项目展示了人脸识别算法的运行效果(无水印),基于MATLAB2022A开发。核心程序包含详细中文注释及操作视频。理论部分介绍了广义回归神经网络(GRNN)、概率神经网络(PNN)、深度神经网络(DNN)和反向传播(BP)神经网络在人脸识别中的应用,涵盖各算法的结构特点与性能比较。
|
存储 分布式计算 MaxCompute
使用PAI-FeatureStore管理风控应用中的特征
PAI-FeatureStore 是阿里云提供的特征管理平台,适用于风控应用中的离线和实时特征管理。通过MaxCompute定义和设计特征表,利用PAI-FeatureStore SDK进行数据摄取与预处理,并通过定时任务批量计算离线特征,同步至在线存储系统如FeatureDB或Hologres。对于实时特征,借助Flink等流处理引擎即时分析并写入在线存储,确保特征时效性。模型推理方面,支持EasyRec Processor和PAI-EAS推理服务,实现高效且灵活的风险控制特征管理,促进系统迭代优化。
577 6
PAI-Rec推荐平台对于实时特征有三个层次
PAI-Rec推荐平台针对实时特征有三个处理层次:1) 离线模拟反推历史请求时刻的实时特征;2) FeatureStore记录增量更新的实时特征,模型特征导出样本准确性达99%;3) 通过callback回调接口记录请求时刻的特征。各层次确保了实时特征的准确性和时效性。
865 0
|
计算机视觉 人工智能
人工智能问题之人脸识别团队决定使用LangChain来构建一个智能排查助手如何解决
人工智能问题之人脸识别团队决定使用LangChain来构建一个智能排查助手如何解决
314 1

热门文章

最新文章