【问题标题】:Tensorflow Extra None dimension required for model模型需要 Tensorflow Extra None 维度
【发布时间】:2020-02-20 15:13:40
【问题描述】:

这是我的模型:

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(40, 40, 3)),
  tf.keras.layers.Dense(150, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10)
])

我的输入张量称为 image_batch 。当我运行np.shape(image_batch[0]) 时,结果是TensorShape([40, 40, 3])。这是预期的行为,因为每个训练示例都是 40x40x3 的 rgb 图像)。 但是,当运行命令predictions = model(image_batch[0]).numpy() 以获取模型的预测时,我得到了错误:

WARNING:tensorflow:Model was constructed with shape Tensor("flatten_1_input:0", shape=(None, 40, 40, 3), dtype=float32) for input (None, 40, 40, 3), but it was re-called on a Tensor with incompatible shape (40, 40, 3).

所以我的问题是为什么 keras 模型需要一个具有额外“无”维度的形状,我如何将它提供给模型?

【问题讨论】:

    标签: python tensorflow keras tensor


    【解决方案1】:

    None 维度是批处理维度。换句话说,输入的形状应该是(batch_size, height, width, num_channels)。

    如果您想预测一个输入,请将model(image_batch[0]).numpy() 更改为model(image_batch[0:1]).numpy()。这将保持第一个维度。在这种情况下,形状将是 (1, 40, 40, 3)。

    【讨论】:

    • 好的,所以“None”可以接受任何维度,如果我想在更大的集合上进行预测,我可以这样做:model(image_batch[0:3]).numpy()对于前 3 个,说(或者是 4 个)
    • 是的,批次维度的大小可以不同。这就是为什么是None。 image_batch[0:3] 将是前三个示例。
    【解决方案2】:

    None 是批次维度。它被设置为无,因为它可以变化。例如,您可以在训练期间使用大小为 512 的批次,然后在预测时使用大小为 1 的批次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 2020-05-14
      • 2020-05-24
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      相关资源
      最近更新 更多