gpt4 book ai didi

python - 如何在 scikit-learn 中获取 LDA 的组件?

转载 作者:IT老高 更新时间:2023-10-28 21:13:57 25 4
gpt4 key购买 nike

在 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中是否有类似的属性?

最佳答案

对于 PCA,文档很清楚。 pca.components_ 是特征向量。

对于 LDA,我们需要 lda.scalings_ 属性。


使用 iris 数据和 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()

结果

Results

关于python - 如何在 scikit-learn 中获取 LDA 的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13973096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com