您的位置:首页 > 其它

scikit-learn---PCA(Principle Component Analysis)---KNN(image classifier)

2018-01-04 23:01 232 查看
摘要:PCA为非监督分类方法,常用于数据降维、为监督分类数据预处理,本例采用PCA对人脸特征提取先做降维处理,然后使用KNN算法对图片进行分类


1.PCA简介

设法将原来变量重新组合成一组新的互相无关的几个综合变量,同时根据实际需要从中可以取出几个较少的综合变量尽可能多地反映原来变量的信息的统计方法叫做主成分分析或称主分量分析,也是数学上用来降维的一种方法。在本例中,主要用于降维处理。

PCA 官方文档

2.KNN

邻近算法,或者说K最近邻(kNN,k-NearestNeighbor)分类算法是数据挖掘分类技术中最简单的方法之一。所谓K最近邻,就是k个最近的邻居的意思,说的是每个样本都可以用它最接近的k个邻居来代表。kNN算法的核心思想是如果一个样本在特征空间中的k个最相邻的样本中的大多数属于某一个类别,则该样本也属于这个类别,并具有这个类别上样本的特性。该方法在确定分类决策上只依据最邻近的一个或者几个样本的类别来决定待分样本所属的类别。 kNN方法在类别决策时,只与极少量的相邻样本有关。由于kNN方法主要靠周围有限的邻近的样本,而不是靠判别类域的方法来确定所属类别的,因此对于类域的交叉或重叠较多的待分样本集来说,kNN方法较其他方法更为适合。

3.code

'''
proprocessing:PCA
test_train:KNN
AUUTHOR:MAC_YJ
TIME:2018.01.04
'''
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import fetch_lfw_people
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split

people=fetch_lfw_people(min_faces_per_person=20,resize=0.7)
'''
image_shapes=people.images[0].shape
fig,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])
'''
mask=np.zeros(people.target.shape,dtype=np.bool)
for target in np.unique(people.target):
mask[np.where(people.target==target)[0][:50]]=1
X_people=people.data[mask]
y_people=people.target[mask]
#scale the grayscale value to be between0 and 1
#instead of 0 and 255 for better numric stability
X_people=X_people/255
#processing:Principle Component Analysis
pca=PCA(n_components=100,whiten=True,random_state=0)
X_train,X_test,y_train,y_test=train_test_split(X_people,y_people,stratify=y_people,random_state=0)
pca.fit(X_train)
X_train_PCA=pca.transform(X_train)
X_test_PCA=pca.transform(X_test)
#KNN
knn=KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train_PCA,y_train)
print('Test set accuracy:{:.2f}'.format(knn.score(X_test_PCA,y_test)))


4.accuracy

In [12]: %run C:\Users\杨景\Desktop\scikit-learn/PCA.py
Test set accuracy:0.31


5.算法优化

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: