model fit/ TypeError: 'NoneType' object is not callable

Viewed 9402

Hello I was trying to run model fit based on the following codes but somehow it keep saying

TypeError: 'NoneType' object is not callable. Not sure which part I have done wrong. THis is

part of my optimization training process. I am lost here... Is there minimum requirement to run such model.fit?

Please help me with this!

    import tensorflow as tf
    from tensorflow.keras import layers
    
    from tensorflow.keras import datasets
    
    (train_x, train_y), (test_x, test_y) = datasets.mnist.load_data()
    
    inputs = layers.Input((28, 28, 1))
    net = layers.Conv2D(32, (3, 3), padding ='SAME')(inputs)
    net = layers.Activation('relu')(net)
    net = layers.Conv2D(32, (3, 3), padding ='SAME')(net)
    net = layers.Activation('relu')(net)
    net = layers.MaxPooling2D(pool_size=(2, 2))(net)
    net = layers.Dropout(0.25)(net)
    
    net = layers.Conv2D(64, (3, 3), padding ='SAME')(net)
    net = layers.Activation('relu')(net)
    net = layers.Conv2D(64, (3, 3), padding ='SAME')(net)
    net = layers.Activation('relu')(net)
    net = layers.MaxPooling2D(pool_size=(2, 2))(net)
    net = layers.Dropout(0.25)(net)
    
    net = layers.Flatten()(net)
    net = layers.Dense(512)(net)
    net = layers.Activation('relu')(net)
    net = layers.Dropout(0.5)(net)
    net = layers.Dense(10)(net)
    net = layers.Activation('softmax')(net)
    
    model = tf.keras.Model(inputs=inputs, outputs=net, name='Basic_CNN')
    
    loss_fun = tf.keras.losses.sparse_categorical_crossentropy 
    
    metrics = tf.keras.metrics.Accuracy() 
    
    optm = tf.keras.optimizers.Adam()
    
    model.compile(optimizer=tf.keras.optimizers.Adam(), 
                  loss='sparse_categorical_crossentropy', 
                  metrics=[tf.keras.metrics.Accuracy()])
    
    train_x.shape, train_y.shape
    
    test_x.shape, test_y.shape
    
    import numpy as np
    
    np.expand_dims(train_x, -1).shape
    
    tf.expand_dims(train_x, -1).shape
    
    train_x = train_x[..., tf.newaxis]
    test_x = test_x[..., tf.newaxis]
    train_x.shape
    
    np.min(train_x), np.max(train_x)
    
    train_x = train_x / 255.
    test_x = test_x / 255.
    
    np.min(train_x), np.max(train_x)
    
    num_epochs = 1
    batch_size = 32
    
    model.fit(train_x, train_y,
              batch_size=batch_size,
              shuffle=True,
              epochs=num_epochs)



    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-20-870033ef5c40> in <module>
          2           batch_size=batch_size,
          3           shuffle=True,
    ----> 4           epochs=num_epochs)
    
    ~/opt/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py in _method_wrapper(self, *args, **kwargs)
        106   def _method_wrapper(self, *args, **kwargs):
        107     if not self._in_multi_worker_mode():  # pylint: disable=protected-access
    --> 108       return method(self, *args, **kwargs)
        109 
        110     # Running inside `run_distribute_coordinator` already.
    
    ~/opt/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
       1096                 batch_size=batch_size):
       1097               callbacks.on_train_batch_begin(step)
    -> 1098               tmp_logs = train_function(iterator)
       1099               if data_handler.should_sync:
       1100                 context.async_wait()
    
    ~/opt/anaconda3/lib/python3.6/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
        778       else:
        779         compiler = "nonXla"
    --> 780         result = self._call(*args, **kwds)
        781 
        782       new_tracing_count = self._get_tracing_count()
    
    ~/opt/anaconda3/lib/python3.6/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
        805       # In this case we have created variables on the first call, so we run the
        806       # defunned version which is guaranteed to never create variables.
    --> 807       return self._stateless_fn(*args, **kwds)  # pylint: disable=not-callable
        808     elif self._stateful_fn is not None:
        809       # Release the lock early so that multiple threads can perform the call
    
    TypeError: 'NoneType' object is not callable
1 Answers

You must do two things.
First you must change loss to: categorical_crossentropy.
Second you need your train_y and test_y have to be one-hot-encoded. That means they must have dimension (number_of_samples, 10), where 10 denotes number of classes. Add this after model.compile():

num_classes = 10 #number of classes, here is 10 (0,1,...,9)
train_y = keras.utils.to_categorical(train_y, num_classes)
test_y = keras.utils.to_categorical(test_y, num_classes)

Finally, let me say this you should change number of epochs and batch size to get better result. For example epochs count = 12 and batch size = 128

Related