成分分析是一种无监督降维,它识别数据差异最大的属性组合
线性判别分析是一种有监督降维,它识别在类别上差异最大的属性组合
import matplotlib.pyplot as plt
from sklearn import dataset
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
# 加载数据集
iris = dataset.load_iris()
X = iris.data
y = iris.target
target_names = iris.target_names
# PCA 投影至二维平面
pca = PCA(n_component = 2)
X_r = pca.fit(X, y).transform(X)
# LDA投影至二维平面
lda = LinearDiscriminantAnalysis(n_component = 2)
X_r2 = lda.fit(X, y).transfrom(X)
# 绘图
colors = ["navy", "turquoise", "darkorange"]
lw = 2
# PCA二维映射图
plt.figure()
for color, i, traget_name in zip(colors, [0, 1, 2], target_names):
plt.scatter(
X_r[y == i, 0], X_r[y == i, 1], color = color, alpha = 0.8, lw = lw, label = target_name
)
plt.legend(loc="best", shadow=False, scatterpoints=1)
plt.title("PCA of IRIS dataset")
# LDA二维映射图
plt.figure()
for color, i, target_name in zip(colors, [0, 1, 2], target_names):
plt.scatter(
X_r2[y == i, 0], X_r2[y == i, 1], color = color, alpha = 0.8,
lw = lw, label = target_name
)
plt.legend(loc="best", shadow=False, scatterpoints=1)
plt.title("PCA of IRIS dataset")
plt.show()
从上述两图便可以看出作为一个有监督的降维方法,LDA主要考虑的是降维后各类间距离最大化,类内距离最小化,因此它的映射图中类别之间存在明显的聚集现象。
PCA作为一种无监督降维方法,主要选取样本之间差别最大的特征作为映射坐标,而并不考虑各类别间间距。



