Keras中有办法立即停止训练吗? [英] Is there a way in Keras to immediately stop training?

查看:496
本文介绍了Keras中有办法立即停止训练吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为tf.keras培训编写自定义的提早停止回调.为此,我可以在其中一个回调函数中设置变量self.model.stop_training = True,例如on_epoch_end().但是,即使我在一个时期的训练中(例如在on_batch_end()中)设置了该变量,Keras也仅在当前时期完成时才停止训练.

I am writing a custom early stopping callback for my tf.keras training. For that I can set the variable self.model.stop_training = True in one of the callback functions, like for example on_epoch_end(). However, Keras stops the training only when the current epoch is done, even if I set this variable within the training of one epoch, for example in on_batch_end().

因此,我的问题是:即使在当前时代的进展中,Keras是否有办法立即停止训练?

Hence my question: Is there a way in Keras to stop training immediately, even within the progress of the current epoch?

推荐答案

您可以使用model.stop_training参数停止培训.

You can use model.stop_training parameter to stop the training.

例如,如果我们想在第二批第三次培训时停止训练,则可以执行以下操作.

For example, if we want to stop the training at 2nd epochs 3rd batch then you can do something like below.

import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
import numpy as np
import pandas as pd

class My_Callback(keras.callbacks.Callback):
    def on_epoch_begin(self, epoch, logs={}):
      self.epoch = epoch

    def on_batch_end(self, batch, logs={}):
        if self.epoch == 1 and batch == 3:
          print (f"\nStopping at Epoch {self.epoch}, Batch {batch}")
          self.model.stop_training = True


X_train = np.random.random((100, 3))
y_train = pd.get_dummies(np.argmax(X_train[:, :3], axis=1)).values

clf = Sequential()
clf.add(Dense(9, activation='relu', input_dim=3))
clf.add(Dense(3, activation='softmax'))
clf.compile(loss='categorical_crossentropy', optimizer=SGD())

clf.fit(X_train, y_train, epochs=10, batch_size=16, callbacks=[My_Callback()])

输出:

Epoch 1/10
100/100 [==============================] - 0s 337us/step - loss: 1.0860
Epoch 2/10
 16/100 [===>..........................] - ETA: 0s - loss: 1.0830
Stopping at Epoch 1, Batch 3
<keras.callbacks.callbacks.History at 0x7ff2e3eeee10>

这篇关于Keras中有办法立即停止训练吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆