Shi*_*iro 8 python keras tensorflow
我试图在keras(Tensorflow后端)中创建一个损失函数,但我有点卡住检查自定义丢失函数的内部.实际上,只有在我编译模型时才会在控制台上显示打印件,之后没有打印件.(我只是测试非常简单的自定义函数,当我解决这个问题时,我将创建真正的函数).我使用train_on_batch函数训练模型.我怎么解决这个问题 ?
def loss_yolo(self, y_true, y_pred):
'''
4*7*7 = 196
1*7*7 = 49
7*7*20 = 980
'''
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))
Run Code Online (Sandbox Code Playgroud)
我的输出:
内部损失功能
批量训练
-0.481604
您唯一可以做的就是不使用python的print函数,而是使用tensorflow的tf.Print函数,该函数是计算图的一部分。文档说该操作不执行任何操作,但是每次对其进行评估时,都会打印一条您可以指定的消息。
您只需要注意将其正确放置在图形中即可,例如:
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))
Run Code Online (Sandbox Code Playgroud)
查看内部发生的事情的更好选择是使用tensorflow调试器。
小智 5
我添加了output_stream参数并在 TensorFlow v2.4.1 中尝试了此代码。工作得很好:
def loss_custom(y_true, y_pred):
d = y_true - y_pred
tf.print("\n y_true:", type(y_true), output_stream=sys.stdout)
return tf.reduce_mean(tf.square(d))
Run Code Online (Sandbox Code Playgroud)
训练期间的输出:
Epoch 1/10
y_true: <class 'tensorflow.python.framework.ops.Tensor'>
1/72 [..............................] - ETA: 0s - loss: 0.2328 - accuracy: 0.3319
y_true: <class 'tensorflow.python.framework.ops.Tensor'>
2/72 [..............................] - ETA: 9s - loss: 0.2087 - accuracy: 0.5250
y_true: <class 'tensorflow.python.framework.ops.Tensor'>
Run Code Online (Sandbox Code Playgroud)