【问题标题】:Cannot execute callback function created using tensorflow无法执行使用 tensorflow 创建的回调函数
【发布时间】:2020-08-09 15:31:35
【问题描述】:

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

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

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

如果有人可以提供一些提示,那将很有帮助。

【问题讨论】:

    标签: python machine-learning keras deep-learning tensorflow2.0


    【解决方案1】:

    错误是由于您的回调类中的拼写错误造成的。在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供您参考。

    【讨论】:

    • 这是一个愚蠢的错误。函数名的一部分是由 pycharm 自动填充的,所以我没有费心去那里检查。谢谢!
    • 您能否提供一些链接,以帮助了解我在帖子中提到的不同版本的激活函数用法?
    • 我主要看 tensorflow 和 keras 网站中描述的教程和指南。我还关注了通过谷歌搜索的几个资源。这里有几个,但做的搜索不多。 keras.io/layers/coretowardsdatascience.com/…missinglink.ai/guides/neural-network-concepts/…。希望这会有所帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多