机器学习笔记——SVM(2)

来源:互联网 发布:linux的版本 编辑:程序博客网 时间:2024/05/22 07:44

支持向量机

SVM+PCA 人脸识别

#!/usr/bin/python# -*- coding: utf-8 -*-from __future__ import print_functionimport matplotlib.pyplot as pltimport logginglogging.basicConfig()from sklearn.model_selection import train_test_splitfrom sklearn.model_selection import GridSearchCVfrom sklearn.datasets import fetch_lfw_peoplefrom sklearn.decomposition import PCA# #进行人脸识别的任务,核心算法采用SVMfrom sklearn.svm import SVCfrom sklearn.metrics import confusion_matrixfrom sklearn.metrics import classification_reportprint(__doc__)# ##  lfw—Labeled Faces in the Wild Home# ##用来加载带标记的人脸数据集 该数据集是互联网上收集的知名人士的JPEG图片的集合,所有详细信息均可在官方网站上查看# ##每张照片都集中在一张脸上。 每个通道的每个像素(RGB中的颜色)由范围0.0-1.0的浮点编码。任务称为人脸识别(或识别)# ##给予脸部照片,找到给定训练集的人的姓名 图库)。原始图像为250 x 250像素,但默认切片和调整大小参数可将其缩小为62 x 74# ##min_faces_per_person=70:提取的数据集将仅保留至少具有min_faces_per_person不同图片的人的照片# ## resize=0.4 ::(float,可选,默认为0.5)用于调整每张脸部图片大小的比例。lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)# ##通过images.shape返回数据集有多少:实例个数 n_samples=1288 高 h=50 宽 w=37n_samples, h, w = lfw_people.images.shape# 特征向量矩阵:每一行是一个实例 每一列是一个特征值  (1288*1850)X = lfw_people.data# ## X的列数即特征向量的维度n_features = X.shape[1]# ##y即每个实例对应哪个人脸;即目标分类函数的标记 class_label (0 1 2 3 4 5 6)  1288*1# ##['Ariel Sharon' 'Colin Powell' 'Donald Rumsfeld' 'George W Bush''Gerhard Schroeder' 'Hugo Chavez' 'Tony Blair']y = lfw_people.targettarget_names = lfw_people.target_names# ## 将数据拆分成训练集和测试集,拆分为两个矩阵x_train 966*1850、y_train 966*1和两个向量x_test 322*1850、y_test 322*1X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)# ##组成元素的个数n_components = 150pca = PCA(n_components=n_components, svd_solver='randomized',whiten=True).fit(X_train)# ##提取特征点eigenfaceseigenfaces = pca.components_.reshape((n_components, h, w))# ##利用PCA对特征值进行降维# ##降维  X_train_pca 966*150  X_test_pca 322*150X_train_pca = pca.transform(X_train)X_test_pca = pca.transform(X_test)# ###支持向量机的参数<C/gramma>产生参数矩阵:C 对错误部分进行惩罚,gramma 取用特征值中的不同比例param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }# ## 'rbf' 内核系数  “balanced”模式使用y的值自动调整与输入数据中的类频率成反比的权重clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)# ##创建好的模型存在clf里clf = clf.fit(X_train_pca, y_train)##测试集上的模型质量的定量评估# ##获得测试集X_test_pca的预测结果y_predy_pred = clf.predict(X_test_pca)# ##classification_report构建一个显示主要分类指标的文本报告rep = classification_report(y_test, y_pred, target_names=target_names)print(rep)# ##行数即有多少类,即多少人n_classes = target_names.shape[0]# ##行列分别代表预测结果和标记结果,对角线上的数值表示预测正确的数目conmat = confusion_matrix(y_test, y_pred, labels=range(n_classes))print(conmat)# ###使用matplotlib进行定性评估def plot_gallery(images, titles, h, w, n_row=3, n_col=4):    plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))    plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)    for i in range(n_row * n_col):        plt.subplot(n_row, n_col, i + 1)        plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)        plt.title(titles[i], size=12)        plt.xticks(())        plt.yticks(())# 在测试集的一部分绘制预测结果def title(y_pred, y_test, target_names, i):    pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]    true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]    return 'predicted: %s\ntrue:      %s' % (pred_name, true_name)# ##将预测出的人名存在变量prediction_titles中prediction_titles = [title(y_pred, y_test, target_names, i) for i in range(y_pred.shape[0])]# ##输出测试集图像,预测结果作为title;打印出图像plot_gallery(X_test, prediction_titles, h, w)eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]# ##绘制提取过特征向量后的特征脸plot_gallery(eigenfaces, eigenface_titles, h, w)plt.show()

打印出的结果为:

                   precision    recall  f1-score   support     Ariel Sharon       0.53      0.69      0.60        13     Colin Powell       0.74      0.85      0.79        60  Donald Rumsfeld       0.80      0.74      0.77        27    George W Bush       0.91      0.88      0.90       146Gerhard Schroeder       0.81      0.84      0.82        25      Hugo Chavez       0.75      0.60      0.67        15       Tony Blair       0.88      0.81      0.84        36      avg / total       0.84      0.83      0.83       322[[  9   0   1   3   0   0   0] [  2  51   1   5   0   1   0] [  5   1  20   0   0   1   0] [  1  11   1 128   3   0   2] [  0   1   0   1  21   1   1] [  0   2   0   2   1   9   1] [  0   3   2   1   1   0  29]]

Figure1:

这里写图片描述
Figure2:

这里写图片描述
可用

print(clf.best_estimator_)

查看此时SVM最佳的参数搭配;
输出为:

SVC(C=1000.0, cache_size=200, class_weight='balanced', coef0=0.0,  decision_function_shape=None, degree=3, gamma=0.005, kernel='rbf',  max_iter=-1, probability=False, random_state=None, shrinking=True,  tol=0.001, verbose=False)

即C=1000.0,gamma=0.005


这里写图片描述

原创粉丝点击