PCA主成分分析实例及3D可视化(鸢尾花数据集)
内容简介
收集了学习PCA的两个鸢尾花数据实例。
第一个案例:详细复盘了PCA降维课程的内容,将四个特征简化到两个,画二维图展示结果;第二个案例:是sklearn上的例子,侧重于3维可视化,所以特征也是简化到3个。原理简介:PCA降维,即将高维数据降到低维。比如原本特征值有4个,经过PCA方法后,选取前两个最重要的特征,将特征值降到2个。
例1: PCA降维流程
1. PCA详细流程
#工具包 import numpy as np import pandas as pd #导入数据 df = pd.read_csv('iris.data') df.columns=['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid', 'class'] #可视化分析-观察四个特征在不同类别的情况 from matplotlib import pyplot as plt import math label_dict = {1: 'Iris-Setosa', 2: 'Iris-Versicolor', 3: 'Iris-Virgnica'} feature_dict = {0: 'sepal length [cm]', 1: 'sepal width [cm]', 2: 'petal length [cm]', 3: 'petal width [cm]'} plt.figure(figsize=(8, 6)) for cnt in range(4): plt.subplot(2, 2, cnt+1) for lab in ('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'): plt.hist(X[y==lab, cnt], label=lab, bins=10, alpha=0.3,) plt.xlabel(feature_dict[cnt]) plt.legend(loc='upper right', fancybox=True, fontsize=8) plt.tight_layout() plt.show()
1234567891011121314151617181920212223242526272829303132333435结果输出:
#切分数据集(这里更新了原课件代码) X = df.values[:,0:4] y = df.values[:,4] #将特征数据标准化 from sklearn.preprocessing import StandardScaler X_std = StandardScaler().fit_transform(X) print (X_std) #打印所有结果 #计算协方差矩阵方法 ##详细版本 mean_vec = np.mean(X_std, axis=0) #计算均值 cov_mat = (X_std - mean_vec).T.dot((X_std - mean_vec)) / (X_std.shape[0]-1) #协方差矩阵 print('Covariance matrix n%s' %cov_mat) ##简单版本 print('NumPy covariance matrix: n%s' %np.cov(X_std.T))
12345678910111213141516上面两个版本计算出的的协方差矩阵结果都是一样的:
仔细观察,可以看到对角线上值约等于1,按对角线对称。
#计算特征值和特征向量 cov_mat = np.cov(X_std.T) eig_vals, eig_vecs = np.linalg.eig(cov_mat) print('Eigenvectors n%s' %eig_vecs) print('nEigenvalues n%s' %eig_vals) 12345
结果显示:
Eigenvalues [ 2.92442837 0.93215233 0.14946373 0.02098259]
#将特征值和特征向量一一对应起来,第一行对应第一个,第二行对应第二个…… # Make a list of (eigenvalue, eigenvector) tuples eig_pairs = [(np.abs(eig_vals[i]), eig_vecs[:,i]) for i in range(len(eig_vals))] print (eig_pairs) print ('----------') # Sort the (eigenvalue, eigenvector) tuples from high to low eig_pairs.sort(key=lambda x: x[0], reverse=True) # Visually confirm that the list is correctly sorted by decreasing eigenvalues print('Eigenvalues in descending order:') for i in eig_pairs: print(i[0]) 123456789101112
#将结果转变成百分数 tot = sum(eig_vals) var_exp = [(i / tot)*100 for i in sorted(eig_vals, reverse=True)] #计算百分数 print (var_exp) cum_var_exp = np.cumsum(var_exp,dtype=list))#计算累加值,比如第一个值1, 第二个值等于第1、2值相加,第三个值等于第1,2,3个值相加…… cum_var_exp 123456
#可视化显示,每个特征值占多少 plt.figure(figsize=(6, 4)) plt.bar(range(4), var_exp, alpha=0.5, align='center', label='individual explained variance') plt.step(range(4), cum_var_exp, where='mid', label='cumulative explained variance') plt.ylabel('Explained variance ratio') plt.xlabel('Principal components') plt.legend(loc='best') plt.tight_layout() plt.show() 123456789101112
从图中更直接地看到,前两个特征比较重要,后面两个特征占比很小,因此只需要取前面两个最重要的特征即可。
#提取前两个特征 matrix_w = np.hstack((eig_pairs[0][1].reshape(4,1), eig_pairs[1][1].reshape(4,1))) print('Matrix W:n', matrix_w) #计算 Y = X_std.dot(matrix_w) Y 123456789
#可视化 #原来的图 plt.figure(figsize=(6, 4)) for lab, col in zip(('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'), ('blue', 'red', 'green')): plt.scatter(X[y==lab, 0], X[y==lab, 1], label=lab, c=col) plt.xlabel('sepal_len') plt.ylabel('sepal_wid') plt.legend(loc='best') plt.tight_layout() plt.show() #降维后的结果 plt.figure(figsize=(6, 4)) for lab, col in zip(('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'), ('blue', 'red', 'green')): plt.scatter(Y[y==lab, 0], Y[y==lab, 1], label=lab, c=col) plt.xlabel('Principal Component 1') plt.ylabel('Principal Component 2') plt.legend(loc='lower center') plt.tight_layout() plt.show()
12345678910111213141516171819202122232425262728结果输出:
降维前二维图:红色和绿色混和在一起
2. 简略流程
这里直接使用sklearn.decomposition降维,更加简单方便。
#导入模块 import numpy as np import matplotlib.pyplot as plt from sklearn import decomposition from sklearn import datasets #导入数据 iris = datasets.load_iris() X = iris.data y = iris.target #建模降维 pca = decomposition.PCA(n_components=2) #降到二维 pca.fit(X) X = pca.transform(X) #作图 plt.figure(figsize=(6, 4)) for name, label in [('Setosa',0), ('Versicolour',1), ('Virginica',2)]: plt.scatter(X[y==label, 0], X[y==label, 1], label=label, ) plt.xlabel('sepal_len') plt.ylabel('sepal_wid') plt.legend(loc='best') plt.tight_layout() plt.show()
1234567891011121314151617181920212223242526272829结果输出:直接使用pca = decomposition.PCA(n_components=2)比之前逐步计算的效果更加好。其中n_components表示保留几个特征值。
例2:PCA example with Iris Data-set 3D可视化
1.建模降维度
#导入数据包 import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import decomposition from sklearn import datasets # 导入函数 np.random.seed(5) centers = [[1, 1], [-1, -1], [1, -1]] iris = datasets.load_iris() X = iris.data y = iris.target # PCA降维度 pca = decomposition.PCA(n_components=3) #降到三维 pca.fit(X) X = pca.transform(X) #打印X看看结果 X
1234567891011121314151617181920212223结果输出:原本有4列数字,现在变成3列了。
2. 3D可视化
#3D图 fig = plt.figure(1, figsize=(4, 3)) plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) plt.cla() for name, label in [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]: ax.text3D(X[y == label, 0].mean(), X[y == label, 1].mean() + 1.5, X[y == label, 2].mean(), name, horizontalalignment='center', bbox=dict(alpha=.5, edgecolor='w', facecolor='w')) # Reorder the labels to have colors matching the cluster results y = np.choose(y, [1, 2, 0]).astype(np.float) ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=plt.cm.nipy_spectral, edgecolor='k') ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) plt.show()
1234567891011121314151617181920212223结果输出:
参考链接:
https://scikit-learn.org/stable/auto_examples/decomposition/plot_pca_iris.html#sphx-glr-auto-examples-decomposition-plot-pca-iris-py
相关知识
鸢尾花数据集上的主成分分析 (PCA) — scikit
PCA实现鸢尾花数据集降维可视化
利用PCA(主成分分析法)实现鸢尾花数据集的分类
鸢尾花数据集降维可视化
主成分分析:PCA的思想及鸢尾花实例实现
机器学习(三)降维之PCA及鸢尾花降维
使用PCA对Iris数据集进行降维和二维分类显示
鸢尾花数据集 — scikit
计算方法实验6:对鸢尾花数据集进行主成分分析(PCA)并可视化
机器学习利用PCA完成鸢尾花数据集的降维与分类
网址: PCA主成分分析实例及3D可视化(鸢尾花数据集) https://www.huajiangbk.com/newsview1947044.html
上一篇: 机器学习:对鸢尾花数据进行PCA |
下一篇: python 打开鸢尾花数据集 |
推荐分享

- 1君子兰什么品种最名贵 十大名 4012
- 2世界上最名贵的10种兰花图片 3364
- 3花圈挽联怎么写? 3286
- 4迷信说家里不能放假花 家里摆 1878
- 5香山红叶什么时候红 1493
- 6花的意思,花的解释,花的拼音 1210
- 7教师节送什么花最合适 1167
- 8勿忘我花图片 1103
- 9橄榄枝的象征意义 1093
- 10洛阳的市花 1039