【问题标题】:How to fix ValueError (x and y should have the same length) while having multiple outputs?如何在有多个输出时修复 ValueError(x 和 y 应该具有相同的长度)?
【发布时间】:2019-06-23 16:04:05
【问题描述】:

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

(灵感来自 J. Goodfellow、Yaroslav Bulatov、Julian Ibarz、Sacha Arnoud 和 维奈 D. 谢特。使用深度卷积神经网络从街景图像中识别多位数字。 CoRR, abs/1312.6082, 2013. 网址 http://arxiv.org/abs/1312.6082 ,遗憾的是他们没有发布他们的网络)。

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 个数组

  • 维度(x_train) = (1000, 130, 130, 1)
    • 其中每张图片为 (130, 130, 1),共有 1000 张图片
  • 维度(y_train) = (1000, 3, 10)

documentation 中说应该是这样的;

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

但是,我不知道如何才能使输出和输入具有相同的长度?

【问题讨论】:

  • 我以前用过多输入多输出模型,第一种方法肯定是要走的路。确保 3 个y 数组(y_train[:, 0, :],...)都具有(1000, 10) 的形状。此外,您编写train_generator 的方式比必要的多一个[ 括号(这通常会引发语法错误,所以我猜您的实际代码中没有。
  • 感谢@Djib2011,对括号有敏锐的眼光,你是对的;)但是,正如我所说,第一种方法给了我一个错误,因为组合输出的长度[y1, y2, y3] 没有与输入的长度相同,因为 [y1, y2, y3] 的形状为 (3,1000,10),尽管我注意每个 y 的形状为 (1000, 10)
  • [y1, y2, y3] 应该是 3 个数组的列表,我不确定它为什么将其视为 组合输入。如果我是你,我会尝试命名输出(例如output1 = keras.layers.Dense(10, activation="softmax", name='out1')),然后尝试在字典中传递标签数组:{'out1': y1, 'out2': y2, 'out3': y3}。也许这会有所帮助...您可能还必须更改 model.compile() 以便使用字典而不是列表,但我不确定。

标签: python tensorflow keras multipleoutputs


【解决方案1】:

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

所以我做了研究,发现仍然有一个 bug(自 2016 年开放!)用于具有单输入和多输出的 ImageDataGenerator。 悲伤的故事。

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

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 2022-06-15
    • 2022-01-23
    • 2021-12-07
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    相关资源
    最近更新 更多