Search code examples
pythontensorflowmachine-learningkeraskeras-layer

How to prevent Tensorflow Input from generating batch dimension


I have recently updated to the newest version of Tensorflow 2.3.1 and after updating my model doesn't work anymore:

model = tf.keras.Sequential([
        layers.Input(shape= input_shape), # input_shape:  (1623, 105, 105, 3)
        layers.experimental.preprocessing.Rescaling(1./255),
        layers.Conv2D(32, 3, activation='relu'),
        layers.MaxPooling2D(),
        layers.Conv2D(32, 3, activation='relu'),
        layers.MaxPooling2D(),
        layers.Conv2D(32, 3, activation='relu'),
        layers.MaxPooling2D(),
        layers.Flatten(),
        layers.Dense(128, activation='relu'),
        layers.Dense(ds_info.features['label'].num_classes)
    ])

The issue is that the Input layer adds a new batch_size dimension, which in turn causes the following error:

Input 0 of layer max_pooling2d_22 is incompatible with the layer: expected ndim=4, found ndim=5. Full shape received: [None, 1623, 103, 103, 32]

How do I prevent that from being generated, or fix this issue.


Solution

  • When specifying input shape, you need to omit the number of samples. That's because Keras can accept any number. So try this:

    layers.Input(shape = input_shape[1:]),
    

    This will specify an input shape of (rows, columns, channels), omitting the number of samples.