如何在scikit-learn中获得LDA的组件? [英] How do I get the components for LDA in scikit-learn?

查看:117
本文介绍了如何在scikit-learn中获得LDA的组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在sklearn中使用PCA时,很容易找出组件:

When using PCA in sklearn, it's easy to get out the components:

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

But I can't for the life of me figure out how to get the components out of LDA, as there is no components_ attribute. Is there a similar attribute in sklearn lda?

推荐答案

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

In the case of PCA, the documentation is clear. The pca.components_ are the eigenvectors.

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

In the case of LDA, we need the lda.scalings_ attribute.

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

结果

这篇关于如何在scikit-learn中获得LDA的组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆