您的位置:首页 > 其它

2.2.2 特征降维(主成分分析)

2019-03-07 20:18 16 查看

import numpy as np
#初始化一个2*2的线性相关矩阵
M=np.array([[1,2],[2,4]])
#计算2*2线性相关矩阵的秩
np.linalg.matrix_rank(M,tol=None)

import pandas as pd
#从互联网读入手写体图片识别任务的训练数据,存储在变量digits_train中
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)

#分割训练数据的特征向量和标记
X_digits=digits_train[np.arange(64)]
y_digits=digits_train[64]

#主成分分析
from sklearn.decomposition import PCA
#初始化一个可以将高纬度特征向量(六十四维)压缩至两个维度的PCA
estimator=PCA(n_components=2)
X_pca=estimator.fit_transform(X_digits)

#显示10类手写数字图片经PCA压缩后的2维空间分布
from matplotlib import pyplot as plt

def plot_pca_scatter():
    colors=['black','blue','purple','yellow','white','red','lime','cyan','orange','gray']
    for i in range(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 principal component')
    plt.ylabel('second principal component')
    plt.show()
plot_pca_scatter()


#对训练数据、测试数据进行特征向量(图片像素)与分类目标的分离
X_train=digits_train[np.arange(64)]
y_train=digits_train[64]
X_test=digits_test[np.arange(64)]
y_test=digits_test[64]

#导入基于线性核的支持向量机分类器
from sklearn.svm import LinearSVC
#使用支持向量机对六十四维度的训练数据建模,并预测
svc=LinearSVC()
svc.fit(X_train,y_train)
y_predict=svc.predict(X_test)

#使用PCA将原六十四维度的图像数据压缩到20个维度
estimator=PCA(n_components=20)
#利用训练特征决定(fit)20个正交维度的方向,并转化(transform)原训练特征
pca_X_train=estimator.fit_transform(X_train)
#测试特征也按照上述的20个正交维度方向进行转化(transform)
pca_X_test=estimator.transform(X_test)
#使用默认配置初始化LinearSVC,对压缩后的二十维特征的训练数据进行建模,
#并在测试数据上预测
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('svc:',svc.score(X_test,y_test))
print(classification_report(y_test,y_predict,target_names=np.arange(10).astype(str)))

print('pca_svc:',pca_svc.score(pca_X_test,y_test))
print(classification_report(y_test,pca_y_predict,target_names=np.arange(10).astype(str)))

 

 

 

 

 

 

 

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