基於SVM的人臉識別

2021-08-28 07:46:09 字數 2492 閱讀 2637

#!/usr/bin/python

# -*- coding: utf-8 -*-

import numpy as np

import matplotlib.pyplot as plt

from sklearn.datasets import fetch_lfw_people

import seaborn as sns; sns.set()

faces = fetch_lfw_people(min_faces_per_person=60)

#print(faces.head())

print(faces.target_names)

print(faces.images.shape)

fig, ax = plt.subplots(3, 5)

for i, axi in enumerate(ax.flat):

axi.imshow(faces.images[i], cmap='bone')

axi.set(xticks=, yticks=,

xlabel=faces.target_names[faces.target[i]])

plt.show()

from sklearn.svm import svc

#from sklearn.decomposition import randomizedpca

from sklearn.decomposition import pca

from sklearn.pipeline import make_pipeline

#利用pca技術將特徵降到150維

pca = pca(n_components=150, whiten=true, random_state=42)

svc = svc(kernel='rbf', class_weight='balanced')

model = make_pipeline(pca, svc)

print(model)

from sklearn.model_selection import train_test_split

xtrain, xtest, ytrain, ytest = train_test_split(faces.data, faces.target,

random_state=42)

#使用grid search cross-validation來選擇我們的引數

from sklearn.grid_search import gridsearchcv

param_grid =

grid = gridsearchcv(model, param_grid=param_grid,cv=5)

grid.fit(xtrain,ytrain)

print(grid.best_params_)

model = grid.best_estimator_

yfit = model.predict(xtest)

print(yfit.shape)

fig, ax = plt.subplots(4, 6)

for i, axi in enumerate(ax.flat):

axi.imshow(xtest[i].reshape(62, 47), cmap='bone')

axi.set(xticks=, yticks=)

axi.set_ylabel(faces.target_names[yfit[i]].split()[-1],

color='black' if yfit[i] == ytest[i] else 'red')

fig.suptitle('predicted names; incorrect labels in red', size=14)

plt.show()

from sklearn.metrics import classification_report

print(classification_report(ytest, yfit,

target_names=faces.target_names))

#精度(precision) = 正確**的個數(tp)/被**正確的個數(tp+fp)

#召回率(recall)=正確**的個數(tp)/**個數(tp+fn)

#f1 = 2精度召回率/(精度+召回率)

from sklearn.metrics import confusion_matrix

mat = confusion_matrix(ytest, yfit)

sns.heatmap(mat.t, square=true, annot=true, fmt='d', cbar=false,

xticklabels=faces.target_names,

yticklabels=faces.target_names)

plt.xlabel('true label')

plt.ylabel('predicted label')

plt.show()

基於SVM的人臉識別分類

from future import print function future 模組,把下乙個新版本的特性匯入到當前版本,於是我們就可以在當前版本中測試一些新版本的特性 我的python版本是3.6.4.所以不需要這個 from time import time 對程式執行時間計時用的 impor...

基於opencv的人臉識別

1前言參考的是 這篇用的是dlib的對齊還加了mask。本文方法 人臉檢測 shiqiyu libfacedetection opencv提取ptr類 2 facedetect.h include include include include include facedetect dll.h us...

基於Opencv的人臉識別

要進行人臉的識別的訓練,首先我們要對openv中人臉識別類facerecognizer要有乙個了解,可以參考這個部落格對facerecognizer 有乙個了解 這個部落格對人臉的訓練解釋的很好,具體怎麼訓練可以閱讀這個部落格。關於人臉識別 我們有一下兩個步驟 1.利用pca變換的人臉識別,對人臉進...