Python 类型错误:'&燃气轮机';在';非类型';和';浮动';
我有这段代码,它在Python3中引发了一个错误,这样的比较可以在Python2上进行 我怎样才能改变它Python 类型错误:'&燃气轮机';在';非类型';和';浮动';,python,tensorflow,machine-learning,keras,typeerror,Python,Tensorflow,Machine Learning,Keras,Typeerror,我有这段代码,它在Python3中引发了一个错误,这样的比较可以在Python2上进行 我怎样才能改变它 import tensorflow as tf def train_set(): class MyCallBacks(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get('acc')>0.95):
import tensorflow as tf
def train_set():
class MyCallBacks(tf.keras.callbacks.Callback):
def on_epoch_end(self,epoch,logs={}):
if(logs.get('acc')>0.95):
print('the training will stop !')
self.model.stop_training=True
callbacks=MyCallBacks()
mnist_dataset=tf.keras.datasets.mnist
(x_train,y_train),(x_test,y_test)=mnist_dataset.load_data()
x_train=x_train/255.0
x_test=x_test/255.0
classifier=tf.keras.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)
])
classifier.compile(
optimizer='sgd',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
history=classifier.fit(x_train,y_train,epochs=20,callbacks=[callbacks])
return history.epoch,history.history['acc'][-1]
train_set()
看来你的错误和我的相似
尝试将
logs.get('acc')
替换为logs.get('accurity')
它在Python2中工作,因为在Python2中可以将None
与float
进行比较,但在Python3中这是不可能的
这条线
logs.get('acc')
返回None
,这就是您的问题
快速解决办法是用
if logs.get('acc') is not None and logs.get('acc') > 0.95:
如果logs.get('acc')
为None
,则上述条件将短路,第二部分logs.get('acc')>0.95
,将不进行评估,因此不会导致上述错误。Tensorflow 2.0
在回调函数中,尝试以下操作:
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
print("---",logs,"---")
'''
if(logs.get('acc')>=0.99):
print("Reached 99% accuracy so cancelling training!")
'''
它给了我这个
--{'loss':0.18487292938232422,'acc':0.94411665}--
我有acc
所以我用了,如果有accurity
我会用accurity
。那么日志和你有什么,然后使用它
TF一直都在经历重大变化,所以安全、非常安全是可以的。我也遇到了同样的问题,我没有使用“acc”,而是将它改为“准确性”。因此,似乎最好尝试将“acc”改为“accurity”。尝试使用try except
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs = {}):
try:
if(logs.get('acc')>0.95):
print("\nReached")
self.model.stop_training = True
except:
if(logs.get('accuracy')>0.95):
print("Reached!!!")
self.model.stop_training = True
使用“acc”而不是“Accurance”,您无需更改。请检查您的行,以查看存储在第一位的精度,然后您可以在需要比较时正确查找
return history.epoch, history.history['acc'][-1]
这里它被称为“acc”,但正如其他人所指出的,它可能是“准确性”请分享整个错误消息。你从那条信息中了解到了什么?这个问题已经有了确切的答案。你的回答补充了什么?
return history.epoch, history.history['acc'][-1]