13.【基础】手写体数字图像--经PCA降维后的LinearSVC

本文所有实现代码均来自《Python机器学习及实战》

#-*- coding:utf-8 -*-

#分别导入numpy、matplotlib、pandas,用于数学运算、作图以及数据分析
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd 

#第一步:使用pandas读取训练数据和测试数据
digits_train = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/optdigits/optdigits.tra',header=None)
digits_test = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/optdigits/optdigits.tes',header=None)

#第二步:分离训练数据的特征向量和标记(不同于上一讲的kmeans,没有操作测试数据)
X_digits = digits_train[np.arange(64)]
y_digits = digits_train[64]

#第三步:PCA降维
from sklearn.decomposition import PCA
#初始化一个可以将高维度的特征向量(64维)压缩至两个维度的PCA
estimator = PCA(n_components=2)
X_pca = estimator.fit_transform(X_digits)
#显示10类(0,1,2,...,9)手写体数字经PCA压缩后的二维分布
import matplotlib.pyplot as plt
def plot_pca_scatter():
    colors=['black','blue','purple','yellow','white','red','lime','cyan','orange','gray']
    for i in xrange(len(colors)):
        px = X_pca[:,0][y_digits.as_matrix()==i]
        py = X_pca[:,1][y_digits.as_matrix()==i]
        plt.scatter(px,py,c=colors[i])
    plt.legend(np.arange(0,10).astype(str))
    plt.xlabel('First Principle Component')
    plt.ylabel('Second Principle Component')
    plt.show()

plot_pca_scatter()
#以上是将64维特征压缩成2维特征,以便肉眼可视化

#第四步:使用原始像素特征和经PCA压缩重建后的地位特征,在相同配置下的支持向量机(分类)模型,分别进行图像识别
X_train = digits_train[np.arange(64)]
y_train = digits_train[64]
X_test = digits_test[np.arange(64)]
y_test = digits_test[64]
#导入默认配置初始化LinearSVC,对原始64维像素特征的训练数据进行建模,并在数据上做出预测,存储在y_predict
from sklearn.svm import LinearSVC
svc = LinearSVC()
svc.fit(X_train,y_train)
y_predict = svc.predict(X_test)
#使用PCA将原64维数据->20维
estimator = PCA(n_components=20)
#利用训练特征决定(fit)20个正交维度的方向,并转化(transform)原训练特征
pca_X_train = estimator.fit_transform(X_train)
pca_X_test = estimator.transform(X_test)
#同样使用默认配置下的LinearSVC,对新的20维像素特征的训练数据进行建模,并在数据上做出预测,存储在pca_y_predict
pca_svc = LinearSVC()
pca_svc.fit(pca_X_train,y_train)
pca_y_predict = pca_svc.predict(pca_X_test)

#第五步:比较两种不同维度的特征在同一个模型下的性能差异
from sklearn.metrics import classification_report
print 'the accuracy of origin data is:',svc.score(X_test,y_test)
print classification_report(y_test,y_predict,target_names=np.arange(10).astype(str))
print 'the accuracy of transformed data is:',pca_svc.score(pca_X_test,y_test)
print classification_report(y_test,pca_y_predict,target_names=np.arange(10).astype(str))

#总结:
#1.尽管经过PCA特征压缩和重建之后的特征数据损失了2%左右的精确性,但是降低了68.75%的维度;
#2.降维/压缩问题是选取数据具有代表性的特征,在保持数据多样性的基础上,规避了大量的特征冗余和噪声;
#3.损失了一部分的精确性,但是大量提升了用于模型训练的时间,效率更高。

补充一张将64维特征降维到2维后的可视化图像:
13.【基础】手写体数字图像--经PCA降维后的LinearSVC_第1张图片

你可能感兴趣的:(机器学习实战)