簡體   English   中英

model fit/ TypeError: 'NoneType' object 不可調用

[英]model fit/ TypeError: 'NoneType' object is not callable

您好,我正在嘗試根據以下代碼運行 model fit,但不知何故它一直在說

TypeError: 'NoneType' object 不可調用。 不確定我做錯了哪一部分。 這是

我的優化訓練過程的一部分。 我在這里迷路了...運行這樣的 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

你必須做兩件事。
首先,您必須將 loss 更改為: categorical_crossentropy
其次,你需要你的train_ytest_y必須是單熱編碼的。 這意味着它們必須具有維度(number_of_samples, 10) ,其中10表示類的數量。 model.compile():之后添加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)

最后,讓我說你應該改變時代數和批量大小以獲得更好的結果。 例如epochs count = 12batch size = 128

當我按名稱引用損失和度量函數時,我遇到了這個錯誤。 在我用對象替換名稱后錯誤消失了。 在您的情況下,我建議添加導入語句並更改 model 編譯參數,即:

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()])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM