支持向量机——人脸识别

svm的算法特性:

1.1训练好的模型的复杂度是由支持向量的个数决定的,而不是由数据的维度决定的。所有svm不太容易产生overfitting。
1.2 svm训练出来的模型完全依赖于支持向量,即使训练集里面的所有并非支持向量的点都被全部去除,重复训练过程,结果仍然会得到一个完全的模型
1.3 一个svm如果训练得出的支持向量个数比较小,svm训练出来的模型比较容易被泛化。

线性不可分情况

1,利用一个非线性的映射把原数据集中的向量点转化到更高的维度的空间中
2,在这个高维度的空间中找一个线性的超平面来根据线性可分的情况处理

代码
from __future__ import print_function
# 计入时间
from time import time
# 打印进程
import logging
# 绘图包
import matplotlib.pyplot as plt
# 机器学习的库
from sklearn.model_selection import train_test_split
from sklearn.datasets import fetch_lfw_people
from  sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import PCA
#支持向量机
from sklearn.svm import SVC
# 将程序进展的信息打印下来

logging.basicConfig(level=logging.INFO,format="%(asctime) %(message)")
# 转载数据集 名人组成的人脸的数据集

lfw_people = fetch_lfw_people(min_faces_per_person=70,resize=0.4)
# 获取数据集的数量,h值和w值
n_samples,h,w = lfw_people.images.shape
# 建立特征向量的矩阵 数据的行
X = lfw_people.data
# 向量的维度,每个人的特征值的数
n_features = X.shape[1]
y = lfw_people.target
# 看数据集中有多少人参与数据集中
target_names = lfw_people.target_names
# 一共 多少类人脸识别
n_classes  = target_names.shape[0]
print("total dataset size:")
print("n_sample:%d" %(n_samples) )
print("n_features:%d"%(n_features))
print("n_classes:%d"%(n_classes))
#  调用数据集,分成训练集 和归类的标记  测试集 和归类的标记
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 = PCA(n_components=n_components,whiten=True).fit(x_train)
print("done in %0.3fs" %(time()-t0))
# 提取人脸的照片的特征值
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))
# 调用支持向量机
print("fitting the classifier to the training set ")
t0=time()
# 参数设置不同的值,尝试不同的值,c是权重,gama就是和函数可以有不同的表现形式,伽马表示多少的特征点可以被使用,取用不同的c和伽马组合最好的和函数,
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("done in %0.3fs"%(time()-t0))
print("best estimator found by grid search:")
# 打印最好的
print(clf.best_estimator_)

print("predicting people 's name on the test set")
t0 = time()


# 预测新来的特征向量,要分的类别
y_pred  = clf.predict(x_test_pca)
print("done in %0.3fs" % (time()-t0))
# 调用classification_report 真实的y和预测的y比较

print(classification_report(y_test,y_pred,labels=None,target_names=target_names))
# confusion_matrix 建立n*N的矩阵,对角线的数据越多准确率越高。
print(confusion_matrix(y_test,y_pred,labels=range(n_classes)))


def polt_gallery(images,titles,h,w,n_row=3,n_col=4):
    # 建立背景图,画布 大小
    plt.figure(figsize=(1.8*n_col,2.4*n_row))
    #建立背景布局
    plt.subplots_adjust(bottom=0,left=0.01,right=0.99,top=0.90,hspace=0.35)
    for i in range(n_row*n_row):
        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,targetnames,i):
    pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]
    ture_name = targetnames[y_test[i]].rsplit(' ', 1)[-1]
    return (pred_name,ture_name)
prediction_titles = [title(y_pred,y_test,target_names,i) for i in range(y_pred.shape[0])]
# 调用函数,
polt_gallery(x_test,prediction_titles,h,w)
# 打印原图和预测的信息
eigenfaces_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
polt_gallery(eigenfaces,eigenfaces_titles,h,w)

plt.show()
结果:

C:\Users\25620\pythonProject1\Scripts\python.exe D:/python/pythonProject1/main.py
total dataset size:
n_sample:1288
n_features:1850
n_classes:7
Extracting the top 150 eigenfaces from 966 faces
done in 0.248s
projecting the input data on the eigenfaces orthonormal basis
done in 0.020s
fitting the classifier to the training set
done in 19.883s
best estimator found by grid search:
SVC(C=1000.0, class_weight=‘balanced’, gamma=0.005)
predicting people 's name on the test set
done in 0.059s
precision recall f1-score support

 Ariel Sharon       0.93      0.72      0.81        18
 Colin Powell       0.81      0.84      0.83        57

Donald Rumsfeld 1.00 0.63 0.78 30
George W Bush 0.81 0.98 0.89 126
Gerhard Schroeder 0.90 0.74 0.81 38
Hugo Chavez 0.89 0.73 0.80 11
Tony Blair 0.95 0.83 0.89 42

     accuracy                           0.85       322
    macro avg       0.90      0.78      0.83       322
 weighted avg       0.87      0.85      0.85       322

[[ 13 4 0 1 0 0 0]
[ 0 48 0 8 0 0 1]
[ 1 3 19 6 1 0 0]
[ 0 2 0 124 0 0 0]
[ 0 1 0 7 28 1 1]
[ 0 0 0 2 1 8 0]
[ 0 1 0 5 1 0 35]]

Process finished with exit code 0

在这里插入图片描述

  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值