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

如何正确调用Model.fit训练输入为二元组的Keras回归模型?

解决tf.keras多输入模型fit调用的IndexError问题

问题根源

model.fit要求多输入数据的每个元素都带有批量维度,且形状与模型输入层定义完全匹配。你当前的输入元组中,第一个数组(128, 1152)缺少批量维度,第二个数组的维度结构也未对齐批量输入要求,导致索引越界错误。

正确调用方式

1. 给输入数据添加批量维度

即使是单样本数据,每个输入数组都需要扩展出批量维度(批量大小设为1):

import numpy as np

# 假设你的输入元组是(arr1, arr2)
arr1 = np.random.rand(128, 1152)  # 原形状(128, 1152)
arr2 = np.random.rand(1, 256)     # 原形状(1, 256)

# 扩展批量维度,变为(1, 128, 1152)和(1, 1, 256)
arr1_batch = np.expand_dims(arr1, axis=0)
arr2_batch = np.expand_dims(arr2, axis=0)
input_batch = (arr1_batch, arr2_batch)

2. 调整标签的形状

单个float类型的标签需要转为批量形式(形状为(1,)):

datapoint_y = 0.5  # 原float标签
y_batch = np.expand_dims(datapoint_y, axis=0)

3. 调用fit方法

使用处理后的批量数据调用fit:

model.fit(x=input_batch, y=y_batch)

验证模型输入层匹配

确保模型输入层的定义与输入数据形状一致,示例如下:

from tensorflow.keras import Input, Model
from tensorflow.keras.layers import Dense, Flatten, concatenate

# 定义输入层,形状对应去掉批量维度后的结构
input1 = Input(shape=(128, 1152))
input2 = Input(shape=(1, 256))

# 后续网络层处理
x1 = Flatten()(input1)
x2 = Flatten()(input2)
concat_layer = concatenate([x1, x2])
output = Dense(1)(concat_layer)

model = Model(inputs=[input1, input2], outputs=output)
model.compile(optimizer='adam', loss='mse')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:01:03