带命名输入的Keras Sequence批量返回格式疑问及报错排查
Keras Sequence处理多命名输入模型的正确返回格式
在拥有命名输入的Keras模型中,使用Keras Sequence处理批量数据时,Sequence需要返回何种格式?现有两种格式备选:
格式1:
{ 'feature_1': [batch_size, time], 'feature_2': [batch_size, time], }
格式2:
[{ # Batch item 1 'feature_1': [time], 'feature_2': [time] }, { # Batch item 2 'feature_1': [time], 'feature_2': [time] }]
给定模型定义:
model = Model( inputs = [feature_1, feature_2], outputs = outputs )
且Input已设置正确名称:
feature_1 = Input(name='feature_1', batch_size=16, shape=(1000,)) feature_2 = Input(name='feature_2', batch_size=16, shape=(1000,))
目前持续报错:
ValueError: Layer "model_1" expects 1 input(s), but it received 16 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, None) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(None, None) dtype=float32>, ... ]
正确返回格式:格式1
你的模型输入是两个独立的Input层(以列表形式传入Model的inputs参数),对应的Keras Sequence需要返回格式1的字典结构,或者也可以返回列表格式[feature_1_batch, feature_2_batch],这两种格式都能和模型的输入层正确匹配。
报错原因
你当前返回的是格式2,这种结构会被Keras解析成16个独立的输入张量(对应设置的batch_size=16),但你的模型仅接受2个输入张量,因此触发了报错(报错信息里的"预期1个输入"是TensorFlow的描述误差,实际模型预期2个输入)。
补充说明
- 返回格式1的字典时,Keras会根据键名自动匹配对应的Input层(因为你已经给Input设置了
name参数),无需手动对应顺序。 - 如果返回列表格式,则需要保证列表内的张量顺序和Model的
inputs参数中的Input层顺序完全一致。
内容的提问来源于stack exchange,提问作者Darren Rahnemoon
相关产品推荐
相关产品推荐

