主成分分析的目标是向量在低维空间中的投影能有很好地近似替代原始向量,但这种投影对分类不一定合适。由于PCA是无监督学习,没有利用样本标签信息,不同类型样本的特征向量在这个空间中的投影可能很接近。线性判别分析也是一种子空间投影技术,但是它的目的是用来分类,让投影后的向量对于分类任务有很好的区分度。
sklearn进行PCA及LDA分析
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import matplotlib
%matplotlib inline
- 1
- 2
- 3
- 4
- 5
# 载入iris数据集
iris = datasets.load_iris()
# 特征向量为4维的
X = iris.data
# 标签值用于将样本显示成不同的颜色
y = iris.target
- 1
- 2
- 3
- 4
- 5
- 6
target_names = iris.target_names
target_names
- 1
- 2
array(['setosa', 'versicolor', 'virginica'], dtype='<U10')
- 1
# 创建LDA降维模型,并计算投影矩阵,对X执行降维操作,得到降维后的结果X_r
lda = LinearDiscriminantAnalysis(n_components = 2)
X_r = lda.fit(X, y).transform(X)
- 1
- 2
- 3
colors = ['navy', 'turquoise', 'darkorange']
plt.figure()
# 显示降维后的样本
for color, i, target_name in zip(colors, [0, 1, 2], target_names):
plt.scatter(X_r[y == i, 0], X_r[y == i, 1], alpha=.8, color=color,label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('LDA of IRIS dataset')
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8