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

ColumnTransformer无get_feature_names_out属性及特征名称获取问题

解决ColumnTransformer无法调用get_feature_names_out()的问题

错误原因

ColumnTransformer.get_feature_names_out()是Scikit-learn 1.0及以上版本才引入的API,若你的Scikit-learn版本低于1.0,就会触发AttributeError: 'ColumnTransformer' object has no attribute 'get_feature_names_out'错误。

解决方案

方案1:升级Scikit-learn到1.0+版本

直接通过pip升级到最新稳定版:

pip install --upgrade scikit-learn

升级完成后,原代码中trained_pipeline.named_steps['preprocessing'].get_feature_names_out()即可正常运行,后续也能直接用select.get_feature_names_out()获取选中的特征名。

方案2:手动生成预处理后的特征名(无需升级版本)

根据你的预处理逻辑,可手动拼接出预处理后的所有特征名:

  1. 数值特征:直接使用你定义的num列表(数值管道仅做填充和缩放,特征名不变)
  2. 分类特征:使用你定义的cat列表(OrdinalEncoder仅对分类列做序数编码,不会生成新列)
  3. 剩余列:提取原数据中不在num和cat里的列(对应remainder='passthrough'的部分)

具体代码实现:

trained_pipeline = clf.best_estimator_

# 获取remainder部分的列名
remainder_cols = [col for col in X_train.columns if col not in num + cat]

# 拼接预处理后的所有特征名
feature_names_before_selection = num + cat + remainder_cols

# 获取选中的特征名
selected_mask = trained_pipeline.named_steps['select'].get_support()
selected_feature_names = [name for name, is_selected in zip(feature_names_before_selection, selected_mask) if is_selected]

print(f"预处理后所有特征名:{feature_names_before_selection}")
print(f"选中的特征名:{selected_feature_names}")

注意事项

  • 若后续将分类管道的OrdinalEncoder替换为OneHotEncoder,则分类特征会生成多列,此时手动生成特征名需要结合OneHotEncoder.get_feature_names_out()来获取编码后的列名,再进行拼接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:40:27