PCA的一個重要應用是特征提取。特征提取背后的思想是,可以找到一種數據表示,比給定的原始表示更適合于分析。特征提取很有用,它的一個很好的應用實例就是圖像。圖像由像素組成,通常存儲于紅綠藍強度。圖像中的對象通常由上千個像素組成,它們只有放在一起才有意義。
下面給出PCA對圖像做特征提取的一個簡單應用,即處理Wild數據集Labeled Faces(標記人臉)中的人臉圖像。這一數據集包含很多互聯網上下載下來的名人臉部圖像,首先看一下這些圖像:
people=fetch_lfw_people(data_home = "C:\\Users\\86185\\Downloads\\",min_faces_per_person=20,resize=.7)
image_shape=people.images[0].shapefix,axes=plt.subplots(2,5,figsize=(15,8),subplot_kw={'xticks':(),'yticks':()})
for target,image,ax in zip(people.target,people.images,axes.ravel()):ax.imshow(image)ax.set_title(people.target_names[target])plt.show()
一共有3023張圖像,每張的像素為87*65,分別屬于62個不同的人:
print('人臉圖片數據集shape:{}'.format(people.images.shape))
print('個數:{}'.format(len(people.target_names)))
但這個數據集有些偏斜,其中包含部分人的大量圖像:
counts=np.bincount(people.target)
for i,(count,name) in enumerate(zip(counts,people.target_names)):print('{0:25}{1:3}'.format(name,count),end=' ')if (i+3)%3==0:print()
為了降低數據偏斜,我們對沒人選取最多50張圖像:
mask=np.zeros(people.target.shape,dtype=np.bool_)
for target in np.unique(people.target):mask[np.where(people.target==target)[0][:50]]=1X_people=people.data[mask]
y_people=people.target[mask]X_people=X_people/255
人臉識別的一個常見任務就是看某個前所未見的人臉是否屬于數據庫中的某個已知人物。這在照片收集、社交媒體和安全應用中都有應用。解決這個問題的方法之一就是構建一個分類器,每個人就是一個單獨類別。但人臉數據庫中通常有許多不同的人,而同一個人的圖像很少。這使得大多數分類器的訓練都很困難。另外,通常要能夠輕松添加新的任務,而不需要重新訓練一個模型。
一種簡單的解決方法就是使用單一最近鄰分類器,尋找與你要分類的人臉最為相似的人臉。這個分類器原則上可以處理每個類別只有一個訓練樣例的情況。
下面以KNeighborsClassifier舉例:
from sklearn.neighbors import KNeighborsClassifierX_train,X_test,y_train,y_test=train_test_split(X_people,y_people,stratify=y_people,random_state=0)
knn=KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train,y_train)
print('精度:{:.2f}'.format(knn.score(X_test,y_test)))
可以看到得到的精度為0.22,平均4-5次識別才能正確識別一個人。