首页 > 解决方案 > 如何在 keras.model.fit_generator 中包含多个输入张量

问题描述

我是一名 keras 菜鸟,在为这个问题苦苦挣扎了很多天之后,我需要一些帮助来使用 keras。如果有任何歧义,请询问更多信息。

目前,我正在尝试从链接修改代码。根据他们的网络模型,预计有 2 个输入张量。现在我在他们提供的源代码中包含 2 个输入张量时遇到了麻烦。

函数 Boneage_prediction_model() 启动 2 个输入张量的模型。

def Boneage_prediction_model():
    i1 = Input(shape=(500, 500, 1), name='input_img') # the 1st input tensor
    i2 = Input(shape=(1,), name='input_gender')       # the 2nd input tensor
    ... ...
    model = Model(inputs=(i1, i2), outputs=o)         # define model input 
                                                        with both i1 and i2
... ... 

#using model.fit_generator to instantiate
# datagen is initiated by keras.preprocessing.image.ImageDataGenerator
# img_train is the 1st network input, and boneage_train is the training label
# gender_train is the 2nd network input  
model.fit_generator(
                     (datagen.flow(img_train, boneage_train, batch_size=10), 
                      gender_train),
                      ... ...
                    ) 

如上所述,我尝试了多种方法将两者结合起来(datagen.flow(img_train, boneage_train, batch_size=10) 和gender_train),但它失败了并不断报告如下错误,

ValueError:检查模型输入时出错:您传递给模型的 Numpy 数组列表不是模型预期的大小。预计会看到 2 个数组,但得到了以下 1 个数组的列表:[array([[[[-0.26078433], [-0.26078433], [-0.26078433], ..., [-0.26078433], [ -0.26078433],[-0.26078433]],[[-0.26078433],[-0.26...

标签: python-3.xkeras

解决方案


如果我理解正确,您希望一个网络有两个输入,组合输出有一个标签。在官方文档中,fit_generator有一个带有多个输入的示例。

使用字典来映射多个输入将导致:

model.fit_generator(
                    datagen.flow({'input_img':img_train, 'input_gender':gender_train}, boneage_train, batch_size=10),
                      ... 
                    ) 


推荐阅读