#本例为人脸识别的SVM算法
#首先fetch_lfw_people导入数据
#其次对数据进行处理,首先得到X,y,分割数据集为训练集和测试集,PCA降维,然后训练
#最后查看正确率,classification_report以及confusion_matrix 以及绘制出特征图和预测结果
from __future__ import print_functionfrom time import time
import logging#程序进展信息
import matplotlib.pyplot as pltimport PIL
from sklearn.model_selection import train_test_split#分割数据集
#from sklearn.cross_validation import train_test_split
from sklearn.datasets import fetch_lfw_people#下载数据集
from sklearn.model_selection import GridSearchCV
#from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
#from sklearn.decomposition import RandomizedPCA
from sklearn.decomposition import PCA
from sklearn.svm import SVCprint(__doc__)#输出文件开头注释的内容"""  """# Display progress logs on stdout
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')###############################################################################
# Download the data, if not already on disk and load it as numpy arrayslfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
#print(lfw_people)
# introspect the images arrays to find the shapes (for plotting)
n_samples, h, w = lfw_people.images.shape#图像矩阵的行h,列w
#print(n_samples,h,w)# 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#y是label,有7个目标时,0-6之间取值
target_names = lfw_people.target_names#实际有哪些名字,这个是一个字符串
n_classes = target_names.shape[0]#shape[0]--行维数 shape[1]--列维数
#print(target_names)print("Total dataset size:")
print("n_samples: %d" % n_samples)
print("n_features: %d" % n_features)
print("n_classes: %d" % n_classes)###############################################################################
# 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)###############################################################################
# Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled
# dataset): unsupervised feature extraction / dimensionality reduction
n_components = 150print("Extracting the top %d eigenfaces from %d faces"% (n_components, X_train.shape[0]))
t0 = time()
#pca = RandomizedPCA(n_components=n_components, whiten=True).fit(X_train)
pca =PCA(svd_solver='randomized',n_components=n_components,whiten=True)
pca.fit(X,y)#训练如何降维
print("done in %0.3fs" % (time() - t0))eigenfaces = pca.components_.reshape((n_components,h,w))#三维
#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))###############################################################################
# Train a SVM classification modelprint("Fitting the classifier to the training set")
t0 = time()
param_grid = {'C': [1e3, 998, 1001, 999, 1002],'gamma': [0.0025, 0.003, 0.0035], }#不停缩小范围
#clf = GridSearchCV(SVC(kernel='rbf', class_weight='auto'), param_grid)
clf=GridSearchCV(SVC(kernel='rbf',class_weight=None),param_grid)#GridSearchCV()第一个参数是分类器
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_)###############################################################################
# Quantitative evaluation of the model quality on the test setprint("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)))###############################################################################
# Qualitative evaluation of the predictions using matplotlibdef 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 setdef 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 eigenfaceseigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
plot_gallery(eigenfaces, eigenface_titles, h, w)plt.show()

人脸识别SVM算法实现--参考麦子学院彭亮机器学习基础5.2相关推荐

  1. 最近邻分类算法KNN实现--参考麦子学院彭亮机器学习基础4.2

    import csv import random import math import operator#导入数据,并分为训练集和测试集 def loadDataset(filename, split ...

  2. 机器学习之决策树算法ID3--参考麦子学院彭亮机器学习基础3.2决策树应用

    #决策树算法 #首先需要导入输入输出数据,并将输入输出数据转换为标准形式 #然后使用sklearn的决策树tree进行处理 #最后输出.dot文件结果,并用Graphviz输出决策树的图形 #对已有的 ...

  3. 麦子学院彭亮python基础_麦子学院python

    教程名称:麦子学院python 麦子学院PYTHON ├─第一阶段:python基础准备 │xa0 ├─1.Web前端开发之HTML+CSS基础入门 │xa0 ├─2.Javascript初步 │xa ...

  4. 人脸识别主要算法原理和公司

    人脸识别主要算法原理和公司 机器视觉与识别|字号 订阅 主流的人脸识别技术基本上可以归结为三类,即:基于几何特征的方法.基于模板的方法和基于模型的方法. 1. 基于几何特征的方法是最早.最传统的方法, ...

  5. 人脸识别的算法基本原理

    人脸识别不管是在手机还是别的什么地方都无疑是一种比较火的解锁方式,看了一篇关于这个算法的文章,写的挺好的,转载一下,共享,感谢原博主辛苦的创作,致敬! 人脸识别主要算法原理 主流的人脸识别技术基本上可 ...

  6. 人脸识别(8)----人脸识别主要算法原理

    人脸识别主要算法原理   [嵌牛导读]:人脸识别,是基于人的脸部特征信息进行身份识别的一种生物识别技术.用摄像机或摄像头采集含有人脸的图像或视频流,并自动在图像中检测和跟踪人脸,进而对检测到的人脸进行 ...

  7. 阿里云人脸识别C#调用示例参考

    概述 前面介绍了关于阿里云人脸识别Java调用示例参考,本文主要介绍C#调用阿里云人脸识别服务,参数等的获取参考阿里云人脸识别使用流程简介. Code Sample 1.使用网络图片 using Sy ...

  8. 阿里云人脸识别C#调用示例参考 1

    概述 前面介绍了关于阿里云人脸识别Java调用示例参考,本文主要介绍C#调用阿里云人脸识别服务,参数等的获取参考阿里云人脸识别使用流程简介. Code Sample 1.使用网络图片 using Sy ...

  9. 阿里云人脸识别PHP调用示例参考

    概述 前面分别给出了关于阿里云人脸识别Java调用示例参考.阿里云人脸识别C#调用示例参考.阿里云人脸识别Python3调用示例参考 .本文主要介绍PHP调用阿里云人脸识别服务,参数等的获取参考阿里云 ...

最新文章

  1. 由于采用分时技术 用户可以独占计算机资源,计算机操作系统第1章练习题
  2. Treasure Exploration
  3. 快搜浏览器_opera、Google、firefox三个浏览器的选择
  4. I00029 C语言程序-打印九九乘法表
  5. idea中自动deployment的步骤
  6. ❤ CSDN精心打造一款插件,让你的浏览器:解锁黑科技、个性十足、沉浸式体验 ❤
  7. 分享WCF文件传输---WCFFileTransfer
  8. 关于JXL读写以及修改EXCEL文件转
  9. 财务数据图表分析,这些财务预算表模板免费用
  10. 旧电脑装什么系统最快_旧电脑装什么系统好 老旧电脑适合装什么操作系统
  11. 【论文阅读】2018-基于深度学习的网络流量分类及异常检测方法研究_王伟
  12. 【OpenGL ES】FBO离屏渲染
  13. 用米思齐mixly和APP INVENTOR 2通过MQTT控制灯亮和熄
  14. Shell脚本之正则表达式以及文本编辑器
  15. LeetCode——缺失数字(C语言)
  16. mysql 系统错误 1058,mysql启动服务报1058错误的解决方法
  17. React实现(Web端)网易云音乐项目(四),错过了真的可惜呀
  18. python csv
  19. <会说话是本事>的记录文摘
  20. 评“最惨创业者”:伪装的道德,轻松绑架了契约精神

热门文章

  1. [附源码]计算机毕业设计SpringBoot高血压分析平台
  2. 一心多用多线程-future-java线程中的异步执行
  3. 通过抓包判断是否支持 802.11k and 11r
  4. IT运维服务的主要内容
  5. 机器视觉(3)-- 机器视觉与AGV小车
  6. macOS中安装zsh,并配置些重要插件
  7. OJDBC驱动版本区别 [ojdbc14.jar,ojdbc5.jar跟ojdbc6.jar的区别]
  8. 网络分析仪 smith圆图调试
  9. 如何学习一门新的计算机语言
  10. 不小心删除了ubuntu的内核,进不去系统和Biss,解决办法。