You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决SelectKBest的NotFittedError报错问题

问题解决:SelectKBest 未拟合错误

错误原因

你的代码里存在语法错误:把fs.fit=(features_train, los_icu_train)写成了赋值语句,而非调用fit()方法。这导致SelectKBest实例根本没有完成拟合流程,后续调用transform方法、访问scores_属性自然会触发未拟合错误。

修正后的完整代码

# 相关性特征选择
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_regression
from matplotlib import pyplot

def select_features(features_train, los_icu_train, features_test):
    fs = SelectKBest(score_func=f_regression, k='all')  # 配置为选择所有特征
    fs.fit(features_train, los_icu_train)  # 从训练数据中学习特征与目标的关联
    features_train_fs = fs.transform(features_train)  # 转换训练输入数据
    features_test_fs = fs.transform(features_test)  # 转换测试输入数据
    return features_train_fs, features_test_fs, fs

features_train_fs, features_test_fs, fs = select_features(features_train, los_icu_train, features_test)  # 执行特征选择
for i in range(len(fs.scores_)):
    print(f'特征 {i}: {fs.scores_[i]:f}')  # 打印各特征的得分

pyplot.bar([i for i in range(len(fs.scores_))], fs.scores_)
pyplot.show()

关键修正点

  • 将fs.fit=(features_train, los_icu_train)改为fs.fit(features_train, los_icu_train):fit是类的内置方法,必须通过括号调用并传入参数,不能用赋值操作代替方法调用。
  • 优化了部分代码格式(如移除冗余空格),并将打印语句改为f-string写法,提升代码可读性。

内容的提问来源于stack exchange,提问作者trailblazer1996

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:36:23