Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keras - ValueError: The first layer in a Sequential model must get an `input_shape` or `batch_input_shape` argument

I'm getting the following error when trying to run a model:

Using TensorFlow backend.
train.py:99: UserWarning: Update your `MaxPooling2D` call to the Keras 2 API: `MaxPooling2D(pool_size=(2, 2), data_format="channels_last")`
  model.add(MaxPooling2D(pool_size=(2, 2), dim_ordering="tf"))
Traceback (most recent call last):
  File "train.py", line 361, in <module>
    save_bottleneck_features()
  File "train.py", line 99, in save_bottleneck_features
    model.add(MaxPooling2D(pool_size=(2, 2), dim_ordering="tf"))
  File "C:\Python35\lib\site-packages\keras\models.py", line 420, in add
    raise ValueError('The first layer in a '
ValueError: The first layer in a Sequential model must get an `input_shape` or `batch_input_shape` argument.

Those are the relevant lines of code (train.py):

model.add(MaxPooling2D(pool_size=(2, 2), dim_ordering="tf"))

In model.py:

def add(self, layer):
        """Adds a layer instance on top of the layer stack.

        # Arguments
            layer: layer instance.

        # Raises
            TypeError: If `layer` is not a layer instance.
            ValueError: In case the `layer` argument does not
                know its input shape.
            ValueError: In case the `layer` argument has
                multiple output tensors, or is already connected
                somewhere else (forbidden in `Sequential` models).
        """
        if not isinstance(layer, Layer):
            raise TypeError('The added layer must be '
                            'an instance of class Layer. '
                            'Found: ' + str(layer))
        if not self.outputs:
            # first layer in model: check that it is an input layer
            if not layer.inbound_nodes:
                # create an input layer
                if not hasattr(layer, 'batch_input_shape'):
                    raise ValueError('The first layer in a '
                                     'Sequential model must '
                                     'get an `input_shape` or '
                                     '`batch_input_shape` argument.')
                # Instantiate the input layer.
                x = Input(batch_shape=layer.batch_input_shape,
                          dtype=layer.dtype, name=layer.name + '_input')
                # This will build the current layer
                # and create the node connecting the current layer
                # to the input layer we just created.
                layer(x)

            if len(layer.inbound_nodes) != 1:
                raise ValueError('A layer added to a Sequential model must '
                                 'not already be connected somewhere else. '
                                 'Model received layer ' + layer.name +
                                 ' which has ' +
                                 str(len(layer.inbound_nodes)) +
                                 ' pre-existing inbound connections.')

            if len(layer.inbound_nodes[0].output_tensors) != 1:
                raise ValueError('All layers in a Sequential model '
                                 'should have a single output tensor. '
                                 'For multi-output layers, '
                                 'use the functional API.')

            self.outputs = [layer.inbound_nodes[0].output_tensors[0]]
            self.inputs = topology.get_source_inputs(self.outputs[0])

            # We create an input node, which we will keep updated
            # as we add more layers
            topology.Node(outbound_layer=self,
                          inbound_layers=[],
                          node_indices=[],
                          tensor_indices=[],
                          input_tensors=self.inputs,
                          output_tensors=self.outputs,
                          # no model-level masking for now
                          input_masks=[None for _ in self.inputs],
                          output_masks=[None],
                          input_shapes=[x._keras_shape for x in self.inputs],
                          output_shapes=[self.outputs[0]._keras_shape])
        else:
            output_tensor = layer(self.outputs[0])
            if isinstance(output_tensor, list):
                raise TypeError('All layers in a Sequential model '
                                'should have a single output tensor. '
                                'For multi-output layers, '
                                'use the functional API.')
            self.outputs = [output_tensor]
            # update self.inbound_nodes
            self.inbound_nodes[0].output_tensors = self.outputs
            self.inbound_nodes[0].output_shapes = [self.outputs[0]._keras_shape]

        self.layers.append(layer)
        self.built = False

How can I solve this issue?

like image 672
Simplicity Avatar asked Jan 05 '23 04:01

Simplicity


1 Answers

From error message

ValueError: The first layer in a Sequential model must get an `input_shape` or `batch_input_shape` argument.

if MaxPooling is the first layer of your model you should pass input_shape (or batch_input_shape) argument like

model.add(MaxPooling2D(pool_size=(2, 2), dim_ordering="tf", input_shape=(16, 16)))
like image 140
kvorobiev Avatar answered Jan 13 '23 19:01

kvorobiev