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

报错ValueError: input_features与feature_names_in_不匹配的解决咨询

解决ValueError: input_features is not equal to feature_names_in_的问题

报错原因

调用ct.get_feature_names_out(Cols_to_encod)时传入了错误参数。ColumnTransformer在fit阶段已经记录了训练数据的完整特征名(存储在feature_names_in_属性中),而你传入的Cols_to_encod只是原始数据中的分类列子集,和feature_names_in_的完整特征列表不匹配,因此触发该报错。

修正方案

直接调用get_feature_names_out()方法(不带参数),它会自动返回所有转换后的特征名,包括独热编码生成的列和未被转换的剩余列:

# categorical columns to encode: Cols_to_encod 
Cols_to_encod = list(X.columns[X.dtypes == 'object'])

# create the transformers
ohe = OneHotEncoder(sparse=False, handle_unknown='ignore')

ct = ColumnTransformer(transformers=[('onehot', ohe, Cols_to_encod)], remainder='passthrough')

X_transformed = ct.fit_transform(X)

# 修正:直接调用get_feature_names_out(),无需传入参数
ohe_names = ct.get_feature_names_out()

额外说明

如果只需要独热编码生成的列名,可以通过前缀筛选提取:

# 获取所有转换后的列名
all_transformed_names = ct.get_feature_names_out()
# 筛选出独热编码对应的列名(前缀为'onehot__')
ohe_only_names = [name for name in all_transformed_names if name.startswith('onehot__')]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:59:57