第十九課 基於sklearn的SVM人臉識別

2021-10-19 10:06:41 字數 3696 閱讀 5092

實驗為基於sklearn的svm人臉識別,使用 svm 演算法對戴眼鏡的人臉和不戴眼鏡的人臉進行分類,從而完成識別戴眼鏡的人臉的任務;實驗涉及的支援向量機引數計算原理,回顧第十八課

人臉影象資料集 olivetti_py3.pkz,儲存在個人資源處,載入資料:

from sklearn.datasets import fetch_olivetti_faces

faces = fetch_olivetti_faces(data_home=

'./'

)

faces.images.shape

# (400, 64, 64)

faces.data.shape

# (400, 4096)

from collections import counter

# 統計 target 中每個取值的數量

count=counter(faces.target)

count

"""counter()

"""

展示前 4 張人臉:

%matplotlib inline 

import matplotlib.pyplot as plt

# 設定子圖數量和畫布大小

plt.figure(num=

4,figsize=(20

,5))

# 遍歷前 4 張和對應的索引(索引從零開始)

for i,face in

enumerate

(faces.images[:4

]):# 1行4列的第i+1個子圖

plt.subplot(1,

4,i+1)

# 在對應位置顯示子圖

# 下面的每個元組代表索引的起始和結束(閉區間)

segments =[(

10,19)

,(30,

32),(

37,38)

,(50,

59),(

63,64)

,(69,

69),(

120,

121),(

124,

129),(

130,

139),(

160,

161),(

164,

169),(

180,

182),(

185,

185),(

189,

189),(

190,

192),(

194,

194),(

196,

199),(

260,

269),(

270,

279),(

300,

309),(

330,

339),(

358,

359),(

360,

369)

]

建立類別標記,戴眼鏡的人臉為 1,沒戴眼鏡的人臉為 0:

import numpy as np

# 先設定所有樣本的標記值為 0

target = np.zeros(faces.target.shape[0]

)# 再將戴眼鏡人臉索引位置的標記值設定為 1

劃分資料集:

from sklearn.model_selection import train_test_split

# 設定測試集的大小為 20%

x_train, x_test, y_train, y_test = train_test_split(faces.data, target, test_size=

0.2, random_state=0)

x_train.shape, x_test.shape, y_train.shape, y_test.shape

# ((320, 4096), (80, 4096), (320,), (80,))

svm 模型訓練:

from sklearn.svm import svc

# 使用線性核函式進行模型訓練

model = svc(kernel=

'linear'

).fit(x_train,y_train)

模型準確率評估:

# 訓練集的準確率

print

('train_accuracy ='

,model.score(x_train,y_train)

)# 測試集的準確率

print

('test_accuracy ='

,model.score(x_test, y_test)

)"""

train_accuracy = 1.0

test_accuracy = 0.9875

"""

識別結果視覺化:

# 測試集的**結果

y_pred = model.predict(x_test)

# 樣本標記值對應的人臉類別

text =

# 設定子圖數量和畫布大小

plt.figure(num=

16,figsize=(20

,20))

# 設定顯示中文字型(黑體)

plt.rcparams[

'font.family']=

['simhei'

]# 遍歷測試集的 16 張人臉對應的特徵向量及其索引

for i,face in

enumerate

(x_test[:16

]):# 4行4列的第i+1個子圖

plt.subplot(4,

4,i+1)

# 將特徵向量轉為二維陣列,shape=(64,64)

face = face.reshape(64,

64)# 將二維陣列以的形式展現出來

plt.imshow(face)

# 取出當前人臉的類別標記**值

label = y_pred[i]

# 在(35,60)的位置標出人臉類別(是否戴眼鏡),字型大小為 24,字型顏色為棕色

第十九課 調整色階

調節的明暗程度,也就是色階的調整 色階 ctrl 表示一幅影象的高光 暗調 中間調,可以調節最暗或最亮的色階,最左端的滑塊代表最暗的值,中間代表中間色調,最右邊的滑塊代表最亮的值。在所有的對話方塊當中,按住alt鍵不放,單擊 取消 則恢復到預設狀態。自動色階 trl shift 自動調整影象明暗程度...

第十九課 物件的構造(下)

學習狄泰軟體學院唐老師c 課程心得,文章內容來自於唐老師課件 一 兩個特殊的建構函式 include class test int getj test const test t main 中test t2 t1時,如果類中只有test const test t 則報錯,需要加上 test main ...

基於NeHe第十九課做的粒子系統

可以實現各種噴射狀的運動狀態,按上下左右鍵分別移動粒子,按y鍵切換顏色,按7 8 9 0切換不同的紋理,按1 2改變粒子速度 按3 4改變粒子大小 particlesys.h particlesys.h inte ce for the cparticlesys class.if defined af...