无法执行使用 tensorflow 创建的回调函数

Cannot execute callback function created using tensorflow

作为 TF 2.0 教程的一部分,我尝试了 TensorFlow 中的回调函数,它使模型能够在达到特定精度或损失值时停止训练。此 Colab 中提供的示例工作正常。我尝试使用 pycharm(使用 tf gpu conda env)在本地 运行 一个类似的示例,但回调函数根本没有执行,并且 运行s 直到最后一个纪元。没有任何错误,代码看起来一样。

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from matplotlib import pyplot as plt
from tensorflow.keras.callbacks import Callback


class MyCallback(Callback):
    def on_epochs_end(self, epoch, logs={}):
        if(logs.get('accuracy') > 0.9):
            print("\n Training stopping now. accuracy reached 90 !")
            self.model.stop_training = True


callback = MyCallback()

# Input data
(training_data, training_labels), (testing_data, testing_labels) = fashion_mnist.load_data()
training_data = training_data / 255.0
testing_data = testing_data / 255.0
plt.imshow(training_data[0], cmap='gray')

# Network
model = Sequential([
    Flatten(input_shape=(28, 28)),
    Dense(units=128, activation='relu'),
    Dense(units=10, activation='softmax')])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(training_data, training_labels, epochs=25, callbacks=[callback])

我指的是一些解决方案的不同示例,我遇到了像
这样的陈述 - activation='relu'
- activation=tf.nn.relu
- activation=tf.keras.activation.relu

用哪个合适?错误是由于不正确的导入引起的吗?

如果有人能给出一些提示,那将会很有帮助。

该错误是由于您的回调 class 中的拼写错误造成的。在 on_epoch_end 函数的定义中,您有一个拼写错误 on_epochs_end。除此之外一切都是正确的。

class MyCallback(Callback):
 #def on_epochs_end(self, epoch, logs={}): # should be epoch (not epochs)
  def on_epoch_end(self, epoch, logs={}):
    if(logs.get('accuracy') > 0.9):
      print("\n Training stopping now. accuracy reached 90 !")
      self.model.stop_training = True

完整代码here供您参考。