模型拟合/类型错误:“NoneType”对象不可调用

Ken*_*Lee 5 python keras tensorflow

您好,我试图根据以下代码运行模型拟合,但不知何故它一直说

类型错误:“NoneType”对象不可调用。不确定我哪一部分做错了。这是

我的优化培训过程的一部分。我在这里迷失了...运行此类 model.fit 是否有最低要求?

请在这件事上给予我帮助!

    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
Run Code Online (Sandbox Code Playgroud)

小智 3

你必须做两件事。
首先,您必须将损失更改为:categorical_crossentropy
其次,您需要train_y并且test_y必须进行单热编码。这意味着它们必须具有维度(number_of_samples, 10),其中10表示类的数量。添加此后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)
Run Code Online (Sandbox Code Playgroud)

最后,我想说的是,你应该改变轮数和批量大小以获得更好的结果。例如epochs count = 12batch size = 128