如何在具有多个输出时修复 ValueError(x 和 y 应该具有相同的长度)?

How to fix ValueError (x and y should have the same length) while having multiple outputs?

我正在建立一个模型,它有一个图像输入 (130,130,1) 和 3 个输出,每个输出包含一个 (10,1) 向量,其中单独应用 softmax。

(Inspired by J. Goodfellow, Yaroslav Bulatov, Julian Ibarz, Sacha Arnoud, and Vinay D. Shet. Multi-digit number recognition from street view imagery using deep convolutional neural networks. CoRR, abs/1312.6082, 2013. URL http://arxiv.org/abs/1312.6082 , sadly they didn't publish their network).

input = keras.layers.Input(shape=(130,130, 1)
l0 = keras.layers.Conv2D(32, (5, 5), padding="same")(input)
[conv-blocks etc]
l12 = keras.layers.Flatten()(l11)
l13 = keras.layers.Dense(4096, activation="relu")(l12)
l14 = keras.layers.Dense(4096, activation="relu")(l13)
output1 = keras.layers.Dense(10, activation="softmax")(l14)
output2 = keras.layers.Dense(10, activation="softmax")(l14)
output3 = keras.layers.Dense(10, activation="softmax")(l14)

model = keras.models.Model(inputs=input, outputs=[output1, output2, output3])
model.compile(loss=['categorical_crossentropy', 'categorical_crossentropy', 
              'categorical_crossentropy'],
              loss_weights=[1., 1., 1.],
              optimizer=optimizer,
              metrics=['accuracy'])

train_generator = train_datagen.flow(x_train,
              [[y_train[:, 0, :], y_train[:, 1, :], y_train[:, 2, :]], 
              batch_size=batch_size)

但是我得到:ValueError:x(图像张量)和 y(标签)应该具有相同的长度。找到:x.shape = (1000, 130, 130, 1), y.shape = (3, 1000, 10)

但是如果我把它改成:

 [same as before]
 train_generator = train_datagen.flow(x_train,
              y_train, 
              batch_size=batch_size)

然后我得到:ValueError:检查模型目标时出错:您传递给模型的 Numpy 数组列表不是模型预期的大小。预计会看到 3 个数组

documentation里面说应该是这样的;

model = Model(inputs=[main_input, auxiliary_input], outputs= 
[main_output, auxiliary_output])

但是,我不知道你应该如何让输出和输入的长度相同?

感谢@Djib2011。当我在文档中查找示例以将其传递到字典中时,我注意到所有示例都使用 model.fit() 而不是 model.fit_generator().

所以我研究了一下,发现还有一个bug(从2016年开始!)for ImageDataGenerator 单输入多输出。 悲伤的故事。

所以解决方案是使用model.fit()而不是model.fit_generator()