#coding:utf-8
# from __future__ import print_function

from time import time #有些步骤要计时,看每个步骤花多长时间
import logging #打印出来progress程序进展
import matplotlib.pyplot as plt #pyplot程序最后把我们预测出来的人脸打印出来,强大的绘图工具

from sklearn.cross_validation import train_test_split
from sklearn.datasets import fetch_lfw_people
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.svm import SVC

print(__doc__)

# Display progress logs on stdout
#打印程序进展的信息
logging.basicConfig(level=logging.INFO,format='%(asctime)s %(message)s') #这个等下可以不用了
#下载数据集,数据的参数可以参考文档
lfw_people = fetch_lfw_people(min_faces_per_person=70,resize=0.4) #

#下面介绍数据预处理和分类
#返回多少个图
n_samples,h,w = lfw_people.images.shape
#X是特征向量的矩阵,每一行是个实例,每一列是个特征值
X = lfw_people.data
#n_featers表示的就是维度
n_features = X.shape[1] #维度:每个人会提取多少的特征值

#提取每个实例对应每个人脸,目标分类标记,不同的人的身份
y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0] #多少行,shape就是多少行,多少个人,多少类

print("Total dataset size:")
print("n_samples:%d" % n_samples) #实例的个数
print("n_features:%d" % n_features) #特征向量的维度
print("n_classes:%d" % n_classes) #总共有多少人

#下面开始拆分数据,分成训练集和测试集,有个现成的函数,通过调用train_test_split;来分成两部分
X_train,X_test,y_train,y_test = train_test_split(
X,y,test_size=0.25)

#数据降维,因为特征值的维度还是比较高
n_components = 150

print("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)
print("done in %0.3fs" % (time() - t0))
#对于人脸的一张照片上提取的特征值名为eigenfaces
eigenfaces = pca.components_.reshape((n_components,h,w))

print("Projecting the inpyt data on the eigenfaces orthonormal basis")
t0 = time()
X_train_pca = pca.transform(X_train) #特征量中训练集所有的特征向量通过pca转换成更低维的矩阵
X_test_pca = pca.transform(X_test)
print("done in %0.3fs" % (time() - t0))

print("Fitting the classifier to the training set")
t0 = time()
#param_grid把参数设置成了不同的值,C:权重;gamma:多少的特征点将被使用,因为我们不知道多少特征点最好,选择了不同的组合
param_grid = {'C':[1e3,5e3,1e4,5e4,1e5],
'gamma':[0.0001,0.0005,0.001,0.005,0.01,0.1],}
#把所有我们所列参数的组合都放在SVC里面进行计算,最后看出哪一组函数的表现度最好
clf = GridSearchCV(SVC(kernel='rbf',class_weight='auto'),param_grid)
#其实建模非常非常简单,主要是数据的预处理麻烦
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_)

#测试集预测看看准确率能到多少
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)))

#把数据可视化的可以看到,把需要打印的图打印出来
def plot_gallery(images,titles,h,w,n_row=3,n_col=4):
"""Helper function to plot a gallery of portraits"""
#在figure上建立一个图当背景
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(())

#把预测的函数归类标签和实际函数归类标签,比如布什
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)

eigenface_titles = ['eigenface %d' %i for i in range(eigenfaces.shape[0])]
#提取过特征向量之后的脸是什么样子
plot_gallery(eigenfaces,eigenface_titles,h,w)

plt.show()

【python】人脸识别的更多相关文章

  1. Python人脸识别最佳教材典范,40行代码搭建人脸识别系统!

    Face Id是一款高端的人脸解锁软件,官方称:"在一百万张脸中识别出你的脸."百度.谷歌.腾讯等各大企业都花费数亿来鞭策人工智能的崛起,而实际的人脸识别技术是否有那么神奇? 绿帽 ...

  2. python人脸识别

    需要掌握知识python,opencv和机器学习一类的基础 过一段时间代码上传github,本人菜j一个,虽然是我自己谢的,也有好多不懂,或者我这就是错误方向 链接:https://pan.baidu ...

  3. 【python人脸识别】使用opencv识别图片中的人脸

    概述: OpenCV是一个基于BSD许可(开源)发行的跨平台计算机视觉库 为什么有OpenCV? 计算机视觉市场巨大而且持续增长,且这方面没有标准API,如今的计算机视觉软件大概有以下三种: 1.研究 ...

  4. Python人脸识别 + 手机推送,老板来了你就会收到短信提示

  5. 总结几个简单好用的Python人脸识别算法

    原文连接:https://mp.weixin.qq.com/s/3BgDld9hILPLCIlyysZs6Q 哈喽,大家好. 今天给大家总结几个简单.好用的人脸识别算法. 人脸识别是计算机视觉中比较常 ...

  6. OpenCV+python 人脸识别

    首先给大家推荐一本书:机器学习算法原理与编程实践 本文内容全部转载于书中,相当于一个读书笔记了吧 绪论 1992年麻省理工学院通过实验对比了基于结构特征的方法与基于模版匹配的方法,发现模版匹配的方法要 ...

  7. 简单的 Python 人脸识别实例

    案例一 导入图片 思路: 1.导入库 2.加载图片 3.创建窗口 4.显示图片 5.暂停窗口 6.关闭窗口 # 1.导入库 import cv2 # 2.加载图片 img = cv2.imread(' ...

  8. python人脸识别项目face-recognition

    该项目基于Github上面的开源项目人脸识别face-recognition,主要是对图像和视频中的人脸进行识别,在开源项目给出的例子基础上对视频人脸识别的KNN算法进行了实现. 0x1 工程项目结构 ...

  9. python 人脸识别试水(一)

    1.安装python,在这里我的版本是python 3.6 2.安装pycharm,我的版本是pycharm 2017 3.安装pip  pip 版本10 4.安装 numpy    :pip ins ...

  10. python 人脸识别

    """Performs face alignment and calculates L2 distance between the embeddings of image ...

随机推荐

  1. ApacheCN React 译文集 20211118 更新

    React 入门手册 零.前言 一.React 和 UI 设计简介 二.创建组件 三.管理用户交互 React 全栈项目 零.前言 一.使用 MERN 释放 React 应用 二.准备开发环境 三.使 ...

  2. 资本主义反抗指南精要(v0.1)

    (1)充分预估工作时间,比如一小时的开发任务,你可以加上技术调研,API/数据库设计,单元测试,联调,集成测试等等,拖到一天,同理一天的任务可以拖到一星期. (2)简历上尽一切手段来美化,最好能包装成 ...

  3. js-reduce方法源码

    // 数组中的reduce方法源码复写 //先说明一下reduce原理:总的一句,reduce方法主要是把数组遍历, //然后把数组的每个元素传入回调函数中,回调函数怎么处理,就会的到什么样的效果 A ...

  4. jvm与dvm两种虚拟机的不同

    jvm : java虚拟机 sun dvm:  dalvik虚拟机  google     区别:         1.基于的架构不同,jvm 基于栈架构,栈是位于内存上的一个空间,执行指令操作,需要 ...

  5. Nodejs ORM框架Sequelize(模型,关联表,事务,循环,及常见问题)

    1.建立连接 const Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'username ...

  6. checkstyle使用介绍

    1.我下载的是checkstyle-5.5-bin.zip:下载地址 http://sourceforge.net/projects/checkstyle/files/ 另一个是checkstyle的 ...

  7. Solution -「Tenka1 2019 D」Three Colors

    \(\mathcal{Description}\)   Link.   给定 \(\{a_n\}\),把每个元素划分入可重集 \(R,G,B\) 中的恰好一个,求满足 \(\sum R,\sum G, ...

  8. 抓取并解密HTTPS流量

    WireShark   Wireshark解密TLS数据流,从网上已有资料来看,主要是两种方式:一是服务端私钥直接解密,二是使用SSLKEYLOGFILE获取握手过程中的会话密钥信息进行解密.   这 ...

  9. 【Python自动化Excel】pandas操作Excel的“分分合合”

    话说Excel数据表,分久必合.合久必分.Excel数据表的"分"与"合"是日常办公中常见的操作.手动操作并不困难,但数据量大了之后,重复性操作往往会令人崩溃. ...

  10. Abp 异常处理

    Abp 异常处理 最近一直在读代码整洁之道,我在读到第三章函数的3.9 使用异常替代返回错误码,其实在我的开发经历中都是使用返回错误码给到前端,之前在阅读ABP官网文档中就有看到过使用异常替代异常的做 ...