模型需要 Tensorflow Extra None 维度
Tensorflow Extra None dimension required for model
这是我的模型:
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 模型需要一个具有额外 "None" 维度的形状,我如何将它提供给模型?
None
维度是批次维度。换句话说,输入的形状应该是 (batch_size, height, width, num_channels)
.
如果要预测一个输入,请将 model(image_batch[0]).numpy()
更改为 model(image_batch[0:1]).numpy()
。这将保持第一个维度。在这种情况下,形状将为 (1, 40, 40, 3)
。
None
是批量维度。它被设置为 None 因为它可以变化。例如,您可以在训练期间使用大小为 512 的批次,然后在预测时使用大小为 1 的批次。
这是我的模型:
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 模型需要一个具有额外 "None" 维度的形状,我如何将它提供给模型?
None
维度是批次维度。换句话说,输入的形状应该是 (batch_size, height, width, num_channels)
.
如果要预测一个输入,请将 model(image_batch[0]).numpy()
更改为 model(image_batch[0:1]).numpy()
。这将保持第一个维度。在这种情况下,形状将为 (1, 40, 40, 3)
。
None
是批量维度。它被设置为 None 因为它可以变化。例如,您可以在训练期间使用大小为 512 的批次,然后在预测时使用大小为 1 的批次。