自动调参(GridSearchCV)及数据降维(PCA)在人脸识别中的应用

来源:互联网 发布:洛阳智网网络和恒凯 编辑:程序博客网 时间:2024/05/20 16:39

1.导入模块

import numpy as npimport pandas as pdfrom pandas import Series,DataFrameimport matplotlib.pyplot as plt%matplotlib inline#向量机from sklearn.svm import SVC#主成分分析(principal components analysis),主要用于数据降维的from sklearn.decomposition import PCA#人脸数据集from sklearn.datasets import fetch_lfw_people# SVM算法的调参工具,可以帮我们选取最适合的参数from sklearn.model_selection import GridSearchCV#用于切割训练数据和样本数据from sklearn.model_selection import train_test_split

2.生成训练数据和测试数据

#从数据集中载入人脸数据faces = fetch_lfw_people(min_faces_per_person=70,resize=0.4)target_names = faces['target_names']data = faces['data']target = faces['target']images = faces['images']#切割训练数据和测试数据X_train,x_test,y_train,y_true = train_test_split(data,target,test_size=0.1)

3.对数据进行降维处理

#创建pca对象pca = PCA(n_components=0.9,whiten=True)#pca理解数据pca.fit(X_train,y_train)#pca进行数据降维转换X_train_pca = pca.transform(X_train)x_test_pca = pca.transform(x_test)

4.创建机器学习模型SVC

svc = SVC(kernel='rbf')

5.使用GridSearchCV来调参

C = [1,3,5,7,9]gamma = [0.0001,0.0005,0.001,0.005,0.01,0.05]#创建GridSearchCV对象,estimator参数是需要进行调参处理的机器学习模型clf = GridSearchCV(svc,param_grid={'C':C,'gamma':gamma})#开始调参(理解数据,确定哪种参数更合适)clf.fit(X_train_pca,y_train)#best_params_来查看选中的最优参数解clf.best_params_

6.使用clf对象对数据进行预测并评分

y_pre = clf.predict(x_test_pca)clf_score = clf.score(x_test_pca,y_true)clf_score

7.展示预测结果

plt.figure(figsize=(12,20))for i in range(100):    plt.subplot(10,10,i+1)    plt.imshow(x_test[i].reshape(50,37),cmap='gray')    true_name = target_names[y_true[i]].split()[-1]    predict_name = target_names[y_pre[i]].split()[-1]    title = 'T:'+true_name+'\nP:'+predict_name    plt.title(title)    plt.axis('off')

这里写图片描述

阅读全文
0 0