问题描述
我正在尝试在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))
输出为
批量培训
-0.481604
-0.481604
推荐答案
您唯一不能做的就是不使用python的打印功能,而是使用tensorflow的 tf.Print 函数,它是计算图的一部分.该文档说,该操作什么都不做,但是每次对其进行评估时,都会打印一条您可以指定的消息.
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中进行训练时,如何在损失功能内打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!