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

结果

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曾小蛙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值