简体   繁体   中英

Creating a Keras Callback that activates every n epochs

I want to create my own Callback in Keras but don't really understand how to do it.

What I want to do is to create a Callback that every n (eg n=10 ) epochs calls a function. According to the Keras documentation ( https://keras.io/callbacks/ ) the base class keras.callbacks.Callback has a property params .

Does this property include the current epoch? And if so, how can it be used/called?

Or is there any other good way to call a function every n epochs?

I had a Callback in mind that works similar as keras.callbacks.ModelCheckpoint when using the argument period=10 .

Help would be really appreciated. Thank you :)

Edit: After quite some reading I came up with this and it seems to work (still needs to test it properly)

class Test1(callbacks.Callback):
    def on_epoch_end(self, epochs, logs={})
        if epochs == 10:
            print('abc') #a random function

callb = Test1()    
model = networks.compute_network(layers=layers, batch_size=batch_size, epochs=epochs, call_list=[callb])
# compute_network in my case loads all the data, trains the network, and then returns it

One site helped me in particular to understand Callbacks better: https://keunwoochoi.wordpress.com/2016/07/16/keras-callbacks/

As @HMK said, on_epoch_begin and on_epoch_end methods provide the current epoch. For example, to apply a function every 10th epochs you can edit your custom callback like that:

class myCallback(keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs=None)
        if epoch % 10 == 0:
            your_func()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM