votes up 3

This model has not yet been built. Build the model first by calling `build()` or calling `fit()` with some data, or specify an `input_shape` argument in the first layer(s) for automatic build.

Package:
Exception Class:
ValueError

Raise code

"""       You can set it to a custom function
            in order to capture the string summary.

    Raises:
        ValueError: if `summary()` is called before the model is built.
    """
    if not self.built:
      raise ValueError('This model has not yet been built. '
                       'Build the model first by calling `build()` or calling '
                       '`fit()` with some data, or specify '
                       'an `input_shape` argument in the first layer(s) for '
                       'automatic build.')
    layer_utils.print_summary(self,
                              line_length=line_length,
                              positions=positions,
      
ūüôŹ Scream for help to Ukraine
Today, 14th August 2022, Russia continues bombing and firing Ukraine. Don't trust Russia, they are bombing us and brazenly lying in same time they are not doing this ūüė†, civilians and children are dying too! We are screaming and asking exactly you to help us, we want to survive, our families, children, older ones.
Please spread the information, and ask your governemnt to stop Russia by any means. We promise to work extrahard after survival to make the world safer place for all.

Ways to fix

votes up 1 votes down

model.summary() was called before building the model. A keras model should be built first before calling the summary method is called.

How to reproduce the error:

  • Install numpy and tensorflow

$ pipenv install tensorflow numpy

  • Sample code

import tensorflow as tf
import numpy as np
class MyModel(tf.keras.Model):


  def __init__(self):
    super(MyModel, self).__init__()
    self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
    self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)


  def call(self, inputs):
    x = self.dense1(inputs)
    return self.dense2(x)


x = np.random.random((4, 3))
y = np.random.randint(0, 2, (4, 1))

# generate random training data
x = np.random.random((4, 3))
y = np.random.randint(0, 2, (4, 1))
# initilize the model
model = MyModel()
model.summary()

Output:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-2-3d3d1ddf02c3> in <module>()
     18 # model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
     19 # model.fit(x,y,epochs=5)
---> 20 model.summary()


/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py in summary(self, line_length, positions, print_fn)
   2475     """
   2476     if not self.built:
-> 2477       raise ValueError('This model has not yet been built. '
   2478                        'Build the model first by calling `build()` or calling '
   2479                        '`fit()` with some data, or specify '


ValueError: This model has not yet been built. Build the model first by calling `build()` or calling `fit()` with some data, or specify an `input_shape` argument in the first layer(s) for automatic build.

Fix

Build the model by calling the build Or fit method of the model object.

import tensorflow as tf
import numpy as np
class MyModel(tf.keras.Model):


  def __init__(self):
    super(MyModel, self).__init__()
    self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
    self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)


  def call(self, inputs):
    x = self.dense1(inputs)
    return self.dense2(x)


x = np.random.random((4, 3))
y = np.random.randint(0, 2, (4, 1))

# generate random training data
x = np.random.random((4, 3))
y = np.random.randint(0, 2, (4, 1))
# initilize the model
model = MyModel()
model.summary()
model.build(input_shape=(None,3))# build the model by calling the build method

Output:

Model: "my_model_7"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_14 (Dense)             multiple                  16        
_________________________________________________________________
dense_15 (Dense)             multiple                  25        
=================================================================
Total params: 41
Trainable params: 41
Non-trainable params: 0
_________________________________________________________________

Also a model can be built if the fit method is called before the summary method.

x = np.random.random((4, 3))
y = np.random.randint(0, 2, (4, 1))
model = MyModel()
model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
model.fit(x,y,epochs=5)
model.summary()

output:

Epoch 1/5
1/1 [==============================] - 0s 401ms/step - loss: 0.3442 - mae: 0.5000 - acc: 0.5000
Epoch 2/5
1/1 [==============================] - 0s 4ms/step - loss: 0.3442 - mae: 0.5000 - acc: 0.5000
Epoch 3/5
1/1 [==============================] - 0s 10ms/step - loss: 0.3441 - mae: 0.5000 - acc: 0.5000
Epoch 4/5
1/1 [==============================] - 0s 11ms/step - loss: 0.3441 - mae: 0.5000 - acc: 0.5000
Epoch 5/5
1/1 [==============================] - 0s 7ms/step - loss: 0.3440 - mae: 0.5000 - acc: 0.5000
Model: "my_model_8"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_16 (Dense)             multiple                  16        
_________________________________________________________________
dense_17 (Dense)             multiple                  25        
=================================================================
Total params: 41
Trainable params: 41
Non-trainable params: 0
_________________________________________________________________

Jun 23, 2021 kellemnegasi answer
kellemnegasi 30.6k

Add a possible fix

Please authorize to post fix