【问题标题】:Stop training model when accuracy reached greater than 0.99当准确率达到大于 0.99 时停止训练模型
【发布时间】:2021-04-23 05:23:53
【问题描述】:

我想阻止我的模型在达到某个阈值后接受训练。我已经为 Tensorflow 的回调编写了一个类。我正在训练 MNIST 数据集。对手写数字进行分类和识别。但由于某种原因,训练并没有停止。我找不到理由。这是我的代码。

import tensorflow as tf

class myCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs={}):
    if(logs.get('accuracy')>0.99):
      print("\nReached 99% accuracy so cancelling training!")
      self.model.stop_training = True

mnist = tf.keras.datasets.mnist

(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)
])
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=10, callbacks=[callbacks])

【问题讨论】:

    标签: python tensorflow machine-learning keras


    【解决方案1】:

    试试这个

    class StopOnPoint(tf.keras.callbacks.Callback):
        def __init__(self, point):
            super(StopOnPoint, self).__init__()
            self.point = point
    
        def on_epoch_end(self, epoch, logs=None): 
            accuracy = logs["accuracy"]
            if accuracy >= self.point:
                self.model.stop_training = True
    
    callbacks = [StopOnPoint(0.98)] # <- set optimal point
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 2017-10-05
      • 2023-03-17
      • 2023-04-04
      相关资源
      最近更新 更多