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

oaxa6hgo  于 2022-11-13  发布在  其他
关注(0)|答案(2)|浏览(226)

你好,我试图运行模型适合基于以下代码,但不知何故,它一直说
TypeError:“NoneType”对象不可调用。不确定我做错了哪一部分。这是
我的优化培训过程的一部分。我在这里迷路了...运行这样的www.example.com有最低要求吗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
bkhjykvo

bkhjykvo1#

你必须做两件事。
首先,您必须将损耗更改为:categorical_crossentropy .
第二,你需要你的train_ytest_y必须是一位热编码的,这意味着它们必须有(number_of_samples, 10)的维度,其中10表示类的数量。

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)

最后,让我说,你应该改变历元的数量和批量大小,以获得更好的结果。

6kkfgxo0

6kkfgxo02#

当我用名称引用损失和度量函数时,我会遇到这个错误。在我用对象替换名称后,错误就消失了。在您的情况下,我建议添加导入语句并更改模型编译参数,即:

from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import SparseCategoricalCrossentropy
from tensorflow.keras.metrics import Accuracy

...

model.compile(optimizer=Adam(), 
        loss=SparseCategoricalCrossentropy(from_logits=True), 
        metrics=[Accuracy()])

相关问题