Author:龙箬
Data Science and Big Data Technology
Change the world with data!
CSDN@weixin_43975035
种子被埋在大雪下安静发芽
老枯树在夜里长出一根新枝丫
而我在爸爸妈妈
看不到的地方
偷偷长大
无监督学习经典模型–特征降维
特征降维
1.主成分分析
线性相关矩阵秩计算样例
import numpy as np
# 初始化一个2*2的线性相关矩阵
M=np.array([[1,2],[2,4]])
# 计算2*2线性相关矩阵的秩
np.linalg.matrix_rank(M,tol=None)
显示手写体数字图片经过PCA压缩后的二维空间分布
# 显示手写体数字图片经过PCA压缩后的二维空间分布
import pandas as pd
# 从互联网读入手写体图片识别任务的训练数据,存储在变量digits_train中
digits_train=pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/optdigits/optdigits.tra',header=None)
# 从互联网读入手写体图片识别任务的测试数据,存储在变量digits_test中
digits_test=pd.read_csv('http://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]
# 从sklearn.decomposition 导入PCA
from sklearn.decomposition import PCA
# 初始化一个可以将高维度特征向量(六十四维)压缩至两个维度的PCA
estimator=PCA(n_components=2)
X_pca=estimator.fit_transform(X_digits)
# 显示10类手写数字图片经PCA压缩后的2维空间分布
import matplotlib.pyplot as plt
def plot_pca_scatter():
colors=['black','blue','purple','yellow','white','red','lime','cyan','orange','gray']
plt.figure(figsize=(14,10))
for i in range(len(colors)):
px=X_pca[:,0][y_digits.values==i]
py=X_pca[:,1][y_digits.values==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.title('PCA Embedding of digits')
plt.show()
plot_pca_scatter()
使用原始像素特征和经PCA压缩重建的低维特征,在相同配置的支持向量机(分类)模型上分别进行图像识别
# 使用原始像素特征和经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]
#导入基于线性核的支持向量机分类器
from sklearn.svm import LinearSVC
# 使用默认配置初始化LinearSVC,对原始六十四维像素特征的训练数据进行建模,并在测试数据上做出预测,存储在y_predict中
svc=LinearSVC(dual=False)
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_y_predict中
pca_svc=LinearSVC(dual=False)
pca_svc.fit(pca_X_train,y_train)
pca_y_predict=pca_svc.predict(pca_X_test)
原始像素特征与PCA压缩重建的低维特征,在相同配置的支持向量机(分类)模型上识别性能的差异
# 原始像素特征与PCA压缩重建的低维特征,在相同配置的支持向量机(分类)模型上识别性能的差异
# 从 sklearn.metrics 导入 classification_report 用于更加细致的分类性能分析
from sklearn.metrics import classification_report
# 对使用原始图像高维像素特征训练的支持向量机分类器的性能做出评估
print(svc.score(X_test,y_test))
print(classification_report(y_test,y_predict,target_names=np.arange(10).astype(str)))
# 对使用PCA压缩重建的低维图像特征训练的支持向量机分类器的性能做出评估
print(pca_svc.score(pca_X_test,y_test))
print(classification_report(y_test,pca_y_predict,target_names=np.arange(10).astype(str)))
运行结果如下:
0.9404563160823595
precision recall f1-score support
0 0.99 0.98 0.99 178
1 0.91 0.93 0.92 182
2 0.99 0.97 0.98 177
3 0.97 0.93 0.95 183
4 0.94 0.97 0.95 181
5 0.89 0.96 0.92 182
6 0.99 0.97 0.98 181
7 0.98 0.91 0.94 179
8 0.89 0.89 0.89 174
9 0.87 0.90 0.89 180
accuracy 0.94 1797
macro avg 0.94 0.94 0.94 1797
weighted avg 0.94 0.94 0.94 1797
0.9287701725097385
precision recall f1-score support
0 0.98 0.96 0.97 178
1 0.89 0.89 0.89 182
2 0.97 0.98 0.97 177
3 0.98 0.91 0.94 183
4 0.94 0.97 0.96 181
5 0.87 0.98 0.92 182
6 0.98 0.97 0.98 181
7 0.96 0.89 0.93 179
8 0.88 0.86 0.87 174
9 0.86 0.88 0.87 180
accuracy 0.93 1797
macro avg 0.93 0.93 0.93 1797
weighted avg 0.93 0.93 0.93 1797
尽管经过PCA特征压缩和重建后的特征数据会损失1%左右的准确率,但是相比于原始数据六十四维度的特征而言,我们却使用PCA压缩并且降低了68.75%的维度。
2.t-SNE降维
显示手写体数字图片经过t-SNE压缩后的二维空间分布
# 显示手写体数字图片经过t-SNE压缩后的二维空间分布
import pandas as pd
# 从互联网读入手写体图片识别任务的训练数据,存储在变量digits_train中
digits_train=pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/optdigits/optdigits.tra',header=None)
# 从互联网读入手写体图片识别任务的测试数据,存储在变量digits_test中
digits_test=pd.read_csv('http://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]
# 从sklearn.manifold 导入t-SNE
from sklearn.manifold import TSNE
# 初始化一个可以将高维度特征向量(六十四维)压缩至两个维度的PCA
ts = TSNE(n_components=2, init= 'pca', random_state=0)
reslut=ts.fit_transform(X_digits)
# 显示10类手写数字图片经t-SNE压缩后的2维空间分布
import matplotlib.pyplot as plt
def plot_tsne_scatter():
colors=['black','blue','purple','yellow','white','red','lime','cyan','orange','gray']
plt.figure(figsize=(14,10))
for i in range(len(colors)):
px=reslut[:,0][y_digits.values==i]
py=reslut[:,1][y_digits.values==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.title('t-SNE Embedding of digits')
plt.show()
plot_tsne_scatter()
从上图中可以看出,对于经典机器学习数据集----手写体数字数据集的识别过程中,t-SNE的降维效果要比主成分分析的降维效果要好很多。
参考致谢:
范淼,李超.Python机器学习及实践——从零开始通往Kaggle竞赛之路
如有侵权,请联系侵删
需要本实验源数据及代码的小伙伴请联系QQ:2225872659