機器學習實戰-SVM模型實現人臉識別

專注的阿熊發表於2022-06-17

from sklearn.decomposition import PCA

import numpy as np

from sklearn.svm import SVC

import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split

from sklearn.decomposition import PCA

from sklearn.metrics import accuracy_score

from sklearn.linear_model import LogisticRegression

from sklearn import datasets

from sklearn.model_selection import GridSearchCV

# 載入人臉資料 lfw->labled faces wild: 野外標記的人臉

data = datasets.fetch_lfw_people(resize = 1, min_faces_per_person = 70)

data

# 進行資料的降維

pca = PCA(n_components=0.95)

X_pca = pca.fit_transform(X)

display(X.shape,X_pca.shape)

svc = SVC()

# C 為懲罰係數 ( 防止過擬合 ) kernel 為核函式型別, tol 為停止訓練的誤差值、精度

params = 外匯跟單gendan5.com{'C':np.logspace(-10,10,50),'kernel':['linear', 'poly', 'rbf', 'sigmoid'],'tol':[0.01,0.001,0.0001]}

gc = GridSearchCV(estimator = svc,param_grid = params,cv = 5)

gc.fit(X_pca,y)

gc.best_params_

svc = SVC(C = 1.8420699693267165e-07,kernel='linear',tol = 0.001)

# 隨機劃分的

X_pca_train,X_pca_test,y_train,y_test, faces_train,faces_test = train_test_split(X_pca,y,faces)

svc.fit(X_pca_train,y_train)

print(' 訓練資料得分: ',svc.score(X_pca_train,y_train))

print(' 測試資料的得分: ',svc.score(X_pca_test,y_test))

plt.figure(figsize=(5 * 2, 10 * 3))

for i in range(50):

     plt.subplot(10,5,i + 1) # 子檢視

     plt.imshow(faces_test[i],cmap = 'gray')

     plt.axis('off') # 刻度關閉

     # 貼上標籤,並且對比實際資料和預測資料

     true_name = target_names[y_test[i]].split(' ')[-1]

     predict_name = target_names[y_pred[i]].split(' ')[-1]

     plt.title(f'True:{true_name}\nPred:{predict_name}')


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2901297/,如需轉載,請註明出處,否則將追究法律責任。

相關文章