今天学习tensorflow回调函数时,遇到了这个错误,经过纠正后代码如下:
import tensorflow as tf
print(tf.__version__)
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(logs.get('accuracy')>0.6):
print("\nReached 60% accuracy so cancelling training!")
self.model.stop_training = True
callbacks = myCallback()
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images=training_images/255.0
test_images=test_images/255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
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(training_images, training_labels, epochs=5, callbacks=[callbacks])
需要注意的是:
logs
似乎get
不到acc
属性,然后我就把acc
改为accuracy
就行了,但我查看Keras
官方文档时却写明存在这个属性
这让我很疑惑。- 如果要使用
accuracy
记得要在model.compile
的时候启用metrics=['accuracy']
。