1.降维解决能问题
降维解决能问题:
- 缓解维度灾难问题;
- 压缩数据的同时让信息损失最小化;
- 理解低维度更容易。
有些特征的意义不大,可以通过降维来解决
2. 主生成分析
2.1 概念
主生成分析(Principal CpmponentAnalysis:PCA)。无监督线性降维,用于数据压缩、消除冗余和消除噪音。
对图书价格关注程度不是很重要,可以通过成分1——成分2进行降维。
映射到蓝色后方差最小。
2.2数学意义
X= [[x11x12 x13…x1p],
[x21 x22 x23…x2p],
…
[xn1 xn2 xn3…xnp]]
= [x1 x2 x3…xp]
其中xj=[x1j x2j…xnj] ( j=1,2,3,…,p)
主成分分析就是将P个观测变量综合成为P个新的变量(综合变量),即:
F1 =a11x1+a12x2+…+a1pxp
F2 =a21x1+a22x2+…+a2pxp
…
Fp =ap1x1+ap2x2+…+appxp
简写
Fj =aj1x1+aj2x2+…+ajpxp(j=1,2,3,…,p )
Fi与 Fj互不相关(i j,i,j= 1,2,3,…,p )
F1的方差 > F2的方差> … > Fp的方差
称为第一主成分F1,为第二主成分F2,…第p主成分Fp
2.3代码
通过from sklearn.decomposition.PCA方法来实现。
import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn import datasets from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler #对红酒降维PCA可视化 def dimension_reduction_for_wine_pca(): scaler =StandardScaler() wine =datasets.load_wine() X = wine.data y = wine.target #由于是无监督学习,所以尽对X进行拟合 X_scaled =scaler.fit_transform(X) # 打印处理后的数据形态 print("处理后的数据形态:",X_scaled.shape)
输出
处理后的数据形态: (178, 13)
降维前有178个样本13个特征。
# 进行PCA处理 pca = PCA(n_components=2)#降到2类 pca.fit(X_scaled) X_pca =pca.transform(X_scaled) # 打印主成分提取后的数据形态 print("主成分提取后的数据形态:", X_pca.shape)
输出
主成分提取后的数据形态: (178, 2)
降维前13个特征减少到2个。
# 将3个分类主成分提取出来 x0 = x_pca[wine.target==0] x1 = x_pca[wine.target==1] x2 = x_pca[wine.target==2] #绘制散点图 plt.scatter(x0[:,0],x0[:,1],c='r',s=60,edgecolor='k') plt.scatter(x1[:,0],x1[:,1],c='g',s=60,edgecolor='k') plt.scatter(x2[:,0],x2[:,1],c='b',s=60,edgecolor='k') #设置图注 plt.legend(wine.target_names,loc='best') plt.xlabel('component 1') plt.ylabel('component 2') plt.show()
#使用主成分绘制热度图 plt.matshow(pca.components_,cmap='plasma') #纵轴为主成分 plt.yticks([0,1],['component 1','component 2']) plt.colorbar() #横轴为原始特征向量 plt.xticks(range(len(wine.feature_names)),wine.feature_names,rotation=60,ha='left') plt.show()
-0.5~0.4,设计到13个特性,数字为正数,与主特征正相关;否则负相关。
2.4特征提取
from sklearn.neural_network import MLPClassifier #特征提取 def pca_for_face(): faces = datasets.fetch_lfw_people(min_faces_per_person=20,resize=0.8) image_shape =faces.images[0].shape #把照片打印出来 fig, axes =plt.subplots(3,4,figsize=(12,9),subplot_kw={'xticks':(),'yticks':()}) for target,image,ax inzip(faces.target,faces.images,axes.ravel()): ax.imshow(image,cmap=plt.cm.gray) ax.set_title(faces.target_names[target]) plt.show()
注意:第一次运行前,可以从第三方网站下载到C:\Users\\scikit_learn_data\lfw_home。可以加快速度。
#用神经网络模型进行训练 X_train,X_test,y_train,y_test = train_test_split(faces.data/255,faces.target,random_state=62) mlp =MLPClassifier(hidden_layer_sizes=[100,100],random_state=62,max_iter=400) mlp.fit(X_train,y_train) print("模型识别准确率:{:.2%}".format(mlp.score(X_test,y_test))) #使用白化功能处理人脸数据 pca =PCA(whiten=True,n_components=0.9,random_state=62).fit(X_train) X_train_whiten =pca.transform(X_train) X_test_whiten =pca.transform(X_test) print("白化后数据形态:{}".format(X_train_whiten.shape)) #使用白化后的神经网络训练 mlp.fit(X_train_whiten,y_train) print("白化后模型识别准确率:{:.2%}".format(mlp.score(X_test_whiten,y_test)))
输出
模型识别准确率:53.84% 白化后数据形态:(2267, 105) 白化后模型识别准确率:57.14%
如此快的时间内,准确率达到53.84%已经很不错了。