PCA Dimensionality Reduction: Simple Face Recognition Model Machine Learning


✌ Actual case: simple face recognition model

1. ✌ Guide library

# 文件目录相关库
import os
# 图片操作库
from PIL import Image
# 导入近邻模型
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# 导入降维函数
from sklearn.decomposition import PCA

2. ✌ Get image data

from PIL import Image
img0=Image.open('D:\\code\\olivettifaces\\'+names[0])
img0.show()

Image.open('file'): Get pictures

3. ✌ Get picture pixel matrix

img0=img0.convert('L')
img0.resize((32,32))
arr=np.array(img0)
arr.ravel()
x=[]
y=[]
for i in names:
	# 获取图片
    img0=Image.open('D:\\code\\olivettifaces\\'+i)
    # 将图片灰度处理
    img0=img0.convert('L')
    # 将尺寸调整为(32,32)像素
    img0=img0.resize((32,32))
    arr=np.array(img0)
    # 获取特征矩阵
    x.append(arr.ravel())
    # 获取标签
    y.append(int(i.split('_')[0]))

img.convert('L'): Process the image to grayscale
img.resize( (32,32) ): Resize the image

4. ✌ Split the data set

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0)

5. ✌ Data without dimensionality reduction

from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# 近邻模型
clf=KNeighborsClassifier()
clf.fit(x_train,y_train)
accuracy_score(y_test,clf.predict(x_test))

Insert picture description here

6. ✌ PCA dimensionality reduction data

from sklearn.decomposition import PCA
# 进行PCA降维,抽取50列特征
pca=PCA(n_components=50)
# 拟合数据
pca.fit(x_train)
# 转化数据集
x_train_pca=pca.transform(x_train)
x_test_pca=pca.transform(x_test)
clf=KNeighborsClassifier()
clf.fit(x_train_pca,y_train)
accuracy_score(y_test,clf.predict(x_test_pca))

Insert picture description here
PCA (n_components=50):
n_components can be an integer, which means to retain the corresponding number of features.
If it is a floating point number from 0 to 1, it means to retain the corresponding percentage of data information

Guess you like

Origin blog.csdn.net/m0_47256162/article/details/113791502