Search code examples
pythontensorflowkerastensor

Tensorflow Extra None dimension required for model


here is my 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)
])

and my input tensor is called image_batch . when I run np.shape(image_batch[0]), the result is TensorShape([40, 40, 3]). This is expected behavior, as each training example is 40x40x3 its an rgb image). However when running the command predictions = model(image_batch[0]).numpy() in order to get the predictions of the model, I get the error:

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).

So my question is why does the keras model expect a shape with an extra "None" dimension, and how do I provide it to the model?


Solution

  • The None dimension is the batch dimension. In other words, the input should have the shape (batch_size, height, width, num_channels).

    If you want to predict on one input, change model(image_batch[0]).numpy() to model(image_batch[0:1]).numpy(). This will maintain the first dimension. The shape will be (1, 40, 40, 3) in this case.