繁体   English   中英

使用 scikit-learn 执行 LDA 降维时出错

[英]error while performing LDA dimensional reduction with scikit-learn

I've got imported the Dataset from this URL in the pandas Dataframe called df : https://www.kaggle.com/jakeshbohaju/brain-tumor?select=Brain+Tumor.csv

但是,在运行线性判别分析时,我总是得到底部的错误。

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
X = df.drop(['label','Image'], axis=1)
y = df[['label']]

lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)

错误:

ValueError                                Traceback (most recent call last) <ipython-input-41-f7a0f19db224> in <module>
     25 lda = LinearDiscriminantAnalysis(n_components=2)
     26 lda2 = LinearDiscriminantAnalysis(n_components=2)
---> 27 X_r3 = lda2.fit(X_train,y_train.values.ravel()).transform(X_train)
     28 X_r2 = lda.fit(X, y).transform(X)
     29 

~/miniforge3/envs/pyM1/lib/python3.8/site-packages/sklearn/discriminant_analysis.py in fit(self, X, y)
    537         else:
    538             if self.n_components > max_components:
--> 539                 raise ValueError(
    540                     "n_components cannot be larger than min(n_features, "
    541                     "n_classes - 1)."

ValueError: n_components cannot be larger than min(n_features, n_classes - 1).

解决方案

lda.fit(X, y)不返回任何内容,因此您不能在其上调用名为.transform()的方法。 API 仅允许您调用已定义的方法。 请参阅文档。

改成这样。 我还鼓励您花更多时间在文档上。

lda = LinearDiscriminantAnalysis(n_components=2)

# either use: lda.fit_transform(X, y)
X_r2 = lda.fit_transform(X, y)

## PREFERRED WAY
# or, use: lda.fit(X, y)
# followed by lda.transform(X)
lda.fit(X, y)
X_r2 = lda.transform(X)

参考

  1. LinearDiscriminantAnalysis - 文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM