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

如何将独热编码与整数混合输入至Keras Sequential模型?

解决Keras模型中混合数值与嵌套one-hot数组输入的问题

你的问题核心在于:Keras的全连接(Dense)层要求输入是二维的纯数值型数组(形状为(样本数量, 总特征数)),但你的DataFrame里包含嵌套的one-hot数组列,转成numpy数组后变成了混合类型的结构,导致模型无法解析输入。下面是具体的解决步骤:

步骤1:展开嵌套的one-hot编码列

把每个包含嵌套数组的列拆分成多个单独的数值列,比如一个长度为7的one-hot数组就拆成7个新列,每个列对应数组中的一个元素。用pandas可以很方便地实现:

# 假设你的one-hot列是'a', 'b', 'd'(根据你给出的第一行数据示例)
one_hot_cols = ['a', 'b', 'd']

for col in one_hot_cols:
    # 将嵌套数组展开为多列
    expanded = df[col].apply(pd.Series)
    # 给新列命名,方便后续识别
    expanded.columns = [f"{col}_{idx}" for idx in expanded.columns]
    # 移除原列,将展开后的列合并到原DataFrame中
    df = pd.concat([df.drop(col, axis=1), expanded], axis=1)

处理完成后,你的DataFrame所有列都会是单个整数/浮点数,不再有嵌套结构。

步骤2:转换为numpy数组并调整模型输入维度

此时再将DataFrame转为numpy数组,得到的就是标准的二维数值数组:

x_train = df.values
# 获取新的特征总数
input_features = df.shape[1]

然后调整你的Keras模型,把input_dim设置为新的特征总数(或者用input_shape=(input_features,),两者效果一致):

from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
# 这里用计算出的input_features替换原来的13
model.add(Dense(130, input_dim=input_features, kernel_initializer='normal', activation='relu'))
model.add(Dense(1, kernel_initializer='normal'))

model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(x_train, y_train, epochs=20, batch_size=128)

为什么之前移除one-hot列能正常运行?

当你移除one-hot列后,DataFrame里剩下的都是单个数值列,转成的numpy数组是标准的二维数值结构,完全符合Dense层对输入的要求,所以模型可以正常训练。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:01:16