Keras中的回调异常-Tensorflow 2.0-Python [英] Exception with Callback in Keras - Tensorflow 2.0 - Python

查看:253
本文介绍了Keras中的回调异常-Tensorflow 2.0-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在与Keras打包在一起的MNIST数据上非常简单地运行了一个顺序Keras模型.

The following code runs a Sequential Keras model, pretty straight forward , on the MNIST data that are packaged with Keras.

在运行以下代码时,我会遇到异常.

In running the following piece of code I get an exception.

该代码易于复制.

import tensorflow as tf

class myCallback(tf.keras.callbacks.Callback):
      def on_epoch_end(self, epoch, logs={}):
        if(logs.get('acc')>0.99):
          print("\nReached 99% accuracy so cancelling training!")
          self.model.stop_training = True

mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

callbacks = myCallback()

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(512, activation=tf.nn.relu),
  tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=10, callbacks=[callbacks])

例外是:

Epoch 1/10
59296/60000 [============================>.] - ETA: 0s - loss: 0.2005 - accuracy: 0.9400

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-f5e673b24d24> in <module>()
     23               metrics=['accuracy'])
     24 
---> 25 model.fit(x_train, y_train, epochs=10, callbacks=[callbacks])

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\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_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    871           validation_steps=validation_steps,
    872           validation_freq=validation_freq,
--> 873           steps_name='steps_per_epoch')
    874 
    875   def evaluate(self,

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py in model_iteration(model, inputs, targets, sample_weights, batch_size, epochs, verbose, callbacks, val_inputs, val_targets, val_sample_weights, shuffle, initial_epoch, steps_per_epoch, validation_steps, validation_freq, mode, validation_in_fit, prepared_feed_values_from_dataset, steps_name, **kwargs)
    406     if mode == ModeKeys.TRAIN:
    407       # Epochs only apply to `fit`.
--> 408       callbacks.on_epoch_end(epoch, epoch_logs)
    409     progbar.on_epoch_end(epoch, epoch_logs)
    410 

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\tensorflow\python\keras\callbacks.py in on_epoch_end(self, epoch, logs)
    288     logs = logs or {}
    289     for callback in self.callbacks:
--> 290       callback.on_epoch_end(epoch, logs)
    291 
    292   def on_train_batch_begin(self, batch, logs=None):

<ipython-input-26-f5e673b24d24> in on_epoch_end(self, epoch, logs)
      3 class myCallback(tf.keras.callbacks.Callback):
      4       def on_epoch_end(self, epoch, logs={}):
----> 5         if(logs.get('acc')>0.99):
      6           print("\nReached 99% accuracy so cancelling training!")
      7           self.model.stop_training = True

TypeError: '>' not supported between instances of 'NoneType' and 'float'

推荐答案

在model.compile函数中,您定义了metrics = ['accuracy'].您需要在logs.get中使用准确性",即logs.get('accuracy').

In model.compile function you defined metrics=['accuracy']. You need to use 'accuracy' in logs.get i.e logs.get('accuracy').

这篇关于Keras中的回调异常-Tensorflow 2.0-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆