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

Joe*_*Joe 17 python machine-learning scikit-learn

在sklearn中使用PCA时,可以轻松获取组件:

from sklearn import decomposition
pca = decomposition.PCA(n_components=n_components)
pca_data = pca.fit(input_data)
pca_components = pca.components_
Run Code Online (Sandbox Code Playgroud)

但我不能为我的生活弄清楚如何从LDA中获取组件,因为没有components_属性.sklearn lda中是否有类似的属性?

mak*_*kis 6

对于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)   
Run Code Online (Sandbox Code Playgroud)

验证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]]
Run Code Online (Sandbox Code Playgroud)

此外,这是绘制双标图并在视觉上进行验证的有用功能:

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()
Run Code Online (Sandbox Code Playgroud)

结果

结果


小智 3

我对代码的解读是,coef_在针对不同类别对样本特征进行评分时,该属性用于对每个组件进行加权。scaling是特征向量,xbar_是平均值。本着 UTSL 的精神,这里是决策函数的来源: https://github.com/scikit-learn/scikit-learn/blob/6f32544c51b43d122dfbed8feff5cd2887bcac80/sklearn/discriminant_analysis.py#L166