在sklearn中使用PCA时,很容易提取出组件:
from sklearn import decomposition
pca = decomposition.PCA(n_components=n_components)
pca_data = pca.fit(input_data)
pca_components = pca.components_但我无论如何也想不出如何从LDA中取出组件,因为没有components_属性。sklearn lda中有没有类似的属性?
发布于 2017-10-18 01:52:58
在主成分分析的情况下,文档是清晰的。 pca.components_ 是特征向量。
在LDA的情况下,我们需要LDA属性。
使用虹膜数据和sklearn的视觉示例:
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
iris = datasets.load_iris()
X = iris.data
y = iris.target
#In general it is a good idea to scale the data
scaler = StandardScaler()
scaler.fit(X)
X=scaler.transform(X)
lda = LinearDiscriminantAnalysis()
lda.fit(X,y)
x_new = lda.transform(X) 验证lda.scalings_是否为特征向量:
print(lda.scalings_)
print(lda.transform(np.identity(4)))
[[-0.67614337 0.0271192 ]
[-0.66890811 0.93115101]
[ 3.84228173 -1.63586613]
[ 2.17067434 2.13428251]]
[[-0.67614337 0.0271192 ]
[-0.66890811 0.93115101]
[ 3.84228173 -1.63586613]
[ 2.17067434 2.13428251]]此外,还提供了一个有用的函数来绘制双线图并进行可视验证:
def myplot(score,coeff,labels=None):
xs = score[:,0]
ys = score[:,1]
n = coeff.shape[0]
plt.scatter(xs ,ys, c = y) #without scaling
for i in range(n):
plt.arrow(0, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5)
if labels is None:
plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center')
else:
plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center')
plt.xlabel("LD{}".format(1))
plt.ylabel("LD{}".format(2))
plt.grid()
#Call the function.
myplot(x_new[:,0:2], lda.scalings_)
plt.show()结果

发布于 2014-02-27 22:17:14
我对代码的理解是,当根据不同的类对样本的特征进行评分时,coef_属性用于对每个组件进行加权。scaling是特征向量,xbar_是平均值。按照UTSL的精神,下面是决策函数的源代码:https://github.com/scikit-learn/scikit-learn/blob/6f32544c51b43d122dfbed8feff5cd2887bcac80/sklearn/discriminant_analysis.py#L166
发布于 2017-10-18 17:04:55
在PCA中,变换操作使用self.components_.T (请参见the code):
X_transformed = np.dot(X, self.components_.T)在LDA中,转换操作使用self.scalings_ (请参阅the code):
X_new = np.dot(X, self.scalings_)
注意.T,它在主成分分析中转置了数组,而不是在LDA中:
components_ : array, shape (n_components, n_features)
scalings_ : array, shape (n_features, n_classes - 1):
https://stackoverflow.com/questions/13973096
复制相似问题