简体   繁体   English

如何在 Keras 的每个时期后禁用打印报告?

[英]How to disable printing reports after each epoch in Keras?

After each epoch I have printout like below:在每个时代之后,我都有如下打印输出:

Train on 102 samples, validate on 26 samples
Epoch 1/1
Epoch 00000: val_acc did not improve
102/102 [==============================] - 3s - loss: 0.4934 - acc: 0.8997 - val_loss: 0.4984 - val_acc: 0.9231

I am not using built-in epochs, so I would like to disable these printouts and print something myself.我没有使用内置的时代,所以我想禁用这些打印输出并自己打印一些东西。

How to do that?怎么做?

I am using tensorflow backend if it matters.如果重要,我正在使用 tensorflow 后端。

verbose=0设置为模型的拟合方法。

First of all, you should set verbose=0 to the fit method for having a silent environment then we need to have a callback for controlling it.首先,您应该将verbose=0设置为 fit 方法以获得静音环境,然后我们需要有一个回调来控制它。 I always use the following code for showing every 10 epochs with its loss.我总是使用下面的代码来显示每 10 个 epoch 的损失。

import tensorflow as tf

class Callback(tf.keras.callbacks.Callback):
    SHOW_NUMBER = 10
    counter = 0
    epoch = 0

    def on_epoch_begin(self, epoch, logs=None):
        self.epoch = epoch

    def on_train_batch_end(self, batch, logs=None):
        if self.counter == self.SHOW_NUMBER or self.epoch == 1:
            print('Epoch: ' + str(self.epoch) + ' loss: ' + str(logs['loss']))
            if self.epoch > 1:
                self.counter = 0
        self.counter += 1

model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, use_multiprocessing=True, callbacks=[Callback()], verbose=0)

Notice that if you increase SHOW_NUMBER , the processing will be finished sooner, so if your epochs are big, you should set it more.请注意,如果您增加SHOW_NUMBER ,处理将更快完成,因此如果您的 epoch 很大,您应该设置更多。

时代

In case anyone doesn't want to implement the progress bar from scratch:如果有人不想从头开始实现进度条:

import tensorflow as tf

class SelectiveProgbarLogger(tf.keras.callbacks.ProgbarLogger):
    def __init__(self, verbose, epoch_interval, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.default_verbose = verbose
        self.epoch_interval = epoch_interval
    
    def on_epoch_begin(self, epoch, *args, **kwargs):
        self.verbose = (
            0 
                if epoch % self.epoch_interval != 0 
                else self.default_verbose
        )
        super().on_epoch_begin(epoch, *args, **kwargs)
model.fit(
    x=..., y=..., 
    batch_size=..., epochs=..., 
    # Set the verbosity level here! This is important.
    callbacks=[SelectiveProgbarLogger(verbose = 1)], 
    # This disables the default `ProgbarLogger`
    verbose=0
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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