在Keras中进行训练时,如何在损失功能内打印? [英] How do I print inside the loss function during training in Keras?

查看:748
本文介绍了在Keras中进行训练时,如何在损失功能内打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Keras(Tensorflow后端)中创建损失函数,但是我有点想检查自定义损失函数的内部.实际上,只有当我编译模型时,打印内容才会出现在控制台上,之后就没有打印内容了. (我只是在测试非常简单的自定义函数,解决此问题时将创建真正的函数).我使用train_on_batch函数训练模型.我该如何解决这个问题?

I am trying to create a loss function in Keras (Tensorflow Backend) but I am a little stuck to check the inside of the custom loss function. In fact, the print appears on the console only when I compile the model, after that there is no print. (I am just testing very simple custom function, I will create the true function when I solved this problem). I train the model using the train_on_batch function. How can I solve this problem?

def loss_yolo(self, y_true, y_pred):  
    print('inside loss function')
    loss = K.mean(y_true - y_pred)
    return loss

model.compile(optimizer='sgd', loss=loss_yolo)

print('train on batch')
print(model.train_on_batch(x, y))

输出为

内部损失函数

inside loss function

批量培训

-0.481604

-0.481604

推荐答案

您唯一不能做的就是不使用python的打印功能,而是使用tensorflow的

The only thing you can do is not use python's print function, but for example, tensorflow's tf.Print function that is part of the computational graph. The documentation says the operation does nothing but each time it is evaluated it prints a message that you can specify.

您只需要注意将其正确放置在图形中即可,例如:

You just need to be careful to place it correctly in the graph, something like:

def loss(y_true, y_pred):
    d = y_true - y_pred
    d = tf.Print(d, [d], "Inside loss function")
    return tf.reduce_mean(tf.square(d))

查看内部情况的一个更好的选择是使用 tensorflow调试器.

A better option to look inside what is going on internally is to use the tensorflow debugger.

这篇关于在Keras中进行训练时,如何在损失功能内打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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