使用 tensorflow keras 训练模型时,如何每 10 个 epoch 打印一行日志?

问题描述 投票:0回答:1

当我为模型拟合时:

model.fit(X, y, epochs=40, batch_size=32, validation_split=0.2, verbose=2)
它为每个纪元打印一条日志行:

Epoch 1/100
0s - loss: 0.2506 - acc: 0.5750 - val_loss: 0.2501 - val_acc: 0.3750
Epoch 2/100
0s - loss: 0.2487 - acc: 0.6250 - val_loss: 0.2498 - val_acc: 0.6250
Epoch 3/100
0s - loss: 0.2495 - acc: 0.5750 - val_loss: 0.2496 - val_acc: 0.6250
.....

如何按如下所示每 10 个时期打印日志行?

Epoch 10/100
0s - loss: 0.2506 - acc: 0.5750 - val_loss: 0.2501 - val_acc: 0.3750
Epoch 20/100
0s - loss: 0.2487 - acc: 0.6250 - val_loss: 0.2498 - val_acc: 0.6250
Epoch 30/100
0s - loss: 0.2495 - acc: 0.5750 - val_loss: 0.2496 - val_acc: 0.6250
.....

python tensorflow keras deep-learning callback
1个回答
2
投票

此回调将创建日志文本文件并将其写入您想要的内容:

log_path = "text_file_name.txt"  # it will be created automatically


class print_training_on_text_every_10_epochs_Callback(Callback):
    def __init__(self, logpath):
        self.logpath = logpath

    def on_epoch_end(self, epoch, logs=None):
        with open(self.logpath, "a") as writefile:  # put log_path here
            with redirect_stdout(writefile):
                if (int(epoch) % 10) == 0:
                    print(
                        f"Epoch: {epoch:>3}"
                        + f" | Loss: {logs['loss']:.4e}"
                        + f" | Accuracy: {logs['accuracy']:.4e}"
                        + f" | Validation loss: {logs['val_loss']:.4e}"
                        + f" | Validation accuracy: {logs['val_accuracy']:.4e}"
                    )
                    writefile.write("\n")


my_callbacks = [
    print_training_on_text_every_10_epochs_Callback(logpath=log_path),
]

你想这样称呼它。

model.fit(
    training_dataset,
    epochs=60,
    verbose=0,  # Important else it still will print the log.
    validation_data=validation_dataset, 
    callbacks=my_callbacks,
)

文本文件只会在 10 个 epochs 过去后更新

这是我在文本文件上得到的

Epoch:   0 | Loss: 5.3454e+00 | Valid loss: 4.2420e-01

Epoch:  10 | Loss: 3.1342e-02 | Valid loss: 3.4554e-02

Epoch:  20 | Loss: 1.6330e-02 | Valid loss: 2.2512e-02

第一个纪元编号为 0,第二个纪元编号为 1,依此类推。

© www.soinside.com 2019 - 2024. All rights reserved.