天天看點

SVM人臉識别技術 自己學着郭亮老師寫的 感覺挺不錯的print(h)#圖檔的多少print(w)#次元print(Y)print(target_names)print(n_class)print(X_train)print(X_test)print(Y_train)print(Y_test)

#-- coding:utf-8 --

from future import print_function#解決python2中的print問題

from time import time#記錄每段處理花費的時間

import logging#記錄進展的狀況

import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split#分割資料集

from sklearn.model_selection import GridSearchCV

from sklearn.metrics import classification_report

from sklearn.datasets import fetch_lfw_people#用來下載下傳資料

from sklearn.metrics import confusion_matrix

from sklearn.decomposition import PCA

from sklearn.svm import SVC#支援向量機

print(doc)#輸出檔案開頭注釋的内容

logging.basicConfig(level=logging.INFO,format=’%(asctime)s%(message)s’)#INFO是指日志按照預處理進行 asctime指進展時間 message指進展内容

lfw_people=fetch_lfw_people(min_faces_per_person=70,resize=0.6)#下載下傳并導入資料

n_samples,h,w=lfw_people.images.shape

#print(lfw_people)

#print(n_samples)#樣本大小

print(h)#圖檔的多少

print(w)#次元

X=lfw_people.data#資料矩陣

#print(X)#

n_features=X.shape[1]#次元大小

#print(n_features)

Y=lfw_people.target#不同人的身份

target_names=lfw_people.target_names#特征向量的類别名 也就是對應的人名

n_class=target_names.shape[0]#有幾個人要區分識别

print(Y)

print(target_names)

print(n_class)

X_train,X_test,Y_train,Y_test=train_test_split(#train_test_split是sklearn自帶的一種劃分資料的函數

X,Y,test_size=0.65,random_state=49

)#訓練集 測試集 訓練集的label 測試集的label

print(X_train)

print(X_test)

print(Y_train)

print(Y_test)

#PCA降維

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,svd_solver=‘randomized’,

whiten=True).fit(X_train)#降維并建立訓練集模型

print(“done in %0.3fs” % (time() - t0))#該過程花費多少時間

#print(pca)

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()

param_grid = {‘C’: [1e3, 5e3, 1e4, 5e4, 1e5],

‘gamma’: [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }#gamma特征函數來建立不同的比例的核函數 對分類的精度來對比嘗試來組成的精度

clf=GridSearchCV(SVC(kernel=‘rbf’,class_weight=‘balanced’),

param_grid,cv=5)#rbf用來處理圖像的特征點,class_weight權重 param_grid核函數

#print(“clf:”,clf)

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_class)))

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(())

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()

SVC

繼續閱讀