【Keras】MNIST99%准确率。训练自动停止报错:TypeError: ‘>‘ not supported between instances of ‘Nonetype‘ and ‘float‘

问题描述

【Tensorflow==1.15.0】使用tf.keras自定义回调函数,设置根据准确率自动停止训练时,报错

TypeError: '>' not supported between instances of 'NoneType' and 'float'
import tensorflow as tf

class myCallback(tf.keras.callbacks.Callback):
    def on_epoch_end(self,epoch,logs={}):
        if(logs.get('accuracy')>0.99):
            print("has  reached 99% accuracy")
            self.model.stop_traning=True          
……省略代码
callbacks=myCallback()
……省略代码
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',  
              metrics=['accuracy' )

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

解决方法

https://github.com/tensorflow/tensorflow/issues/36358

将'accuracy'替换为‘acc’

if(logs.get('accuracy') > ACCURACY_THRESHOLD):
-》》》
if(logs.get('acc') > ACCURACY_THRESHOLD):

完整代码 

import tensorflow as tf

print(tf.__version__)
class myCallback(tf.keras.callbacks.Callback):
    def on_epoch_end(self,epoch,logs={}):
        if(logs.get('acc')>0.99):
            print("has  reached 99% accuracy")
            self.model.stop_traning=True
            
mnist=tf.keras.datasets.mnist  

#path where to cache the dataset locally (relative to ~/.keras/datasets).

#x_train, x_test: uint8 arrays of grayscale image data with shapes (num_samples, 28, 28).
#y_train, y_test: uint8 arrays of digit labels (integers in range 0-9) with shapes (num_samples,).

# 如果mnist.npz在本机上已有此数据集(位于'~/.keras/datasets/),则载入。否则数据将下载到该目录下
(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)
    
]
)
# 当便签是实际数字非one-hot编码时,使用稀疏多类别交叉熵
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',  
              metrics=['accuracy']
                )

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

结果

【Keras】MNIST99%准确率。训练自动停止报错:TypeError: ‘>‘ not supported between instances of ‘Nonetype‘ and ‘float‘_第1张图片

 

你可能感兴趣的:(#,Tensorflow,tensorflow,MNIST,on_epoch_end,训练达到准确率自动停止,简单神经网络)