Olivetti人脸数据集包含400张灰度的64*64像素的人脸图像,每个图像被展平为大小为4096的一维向量,40个不同的人拍照十次。
1、导入数据集。
fetch_olivetti_faces函数导入Olivetti数据集,可以使用olivetti.DESCR查看数据集描述。olivetti.target表示数据集的目标,olivetti.data表示数据集一维向量数据。


2、将数据集拆分为训练集、验证集和测试集。
因为数据集非常小,使用StratifiedShuffleSplit分层抽样来确保每组中每个人的图像数量相同,机器学习交叉验证的数据分割算法有关于拆分的几种方式介绍,StratifiedShuffleSplit是分层随机交叉验证。

3、为了加速训练,使用PCA降维。
PCA保留99%的方差,将4096维降低为199。

4、使用K-Means聚类算法对图像进行归类,测试多个K值。

5、使用silhouette_score轮廓分数为集群选择最佳K值。
best_k值为120时,silhouette_score轮廓分数最高。

6、使用RandomForestClassifier随机森林对PCA降维后训练分类器。
随机森林训练后在验证集上的score为0.925。

7、使用K-Means降维并送入RandomForestClassifier随机森林训练分类器。
但是得分不是很理想,比直接PCA降维后训练分类器要低很多。

8、使用网格搜索GridSearchCV再次搜索最佳的K值。
运行后最好的值也不会超过80%,cluster聚类后的数据没有原始PCA后的数据表现好。

9、使用两种降维数据的总特征再次训练验证。
np.c_是按行连接两个矩阵,增加特征数量。

10、使用 Gaussian mixture 高斯混合模型训练数据集。

11、基于高斯混合模型sample方法生成新数据,pca.inverse_transform还原数据并可视化。

12、对原始数据进行旋转、翻转、变暗处理。

13、对比高斯混合模型在修改后的图形上得到的score_samples相差很大,可以检测到异常。

14、PCA降维用来异常检测
定义函数reconstruction_errors来检测PCA的重建误差均方误差mse,pca.inverse_transform可以将pca降维后的数据还原。

查看训练数据上和修改后的数据上reconstruction_errors,存在较大的区别。

可视化重建后的修改后的数据,发现重建数据不能表示原来的图像。

网友评论