首页 > 解决方案 > 在 Keras 中调用 model.fit 时无法从损失函数运行打印语句

问题描述

我创建了一个名为的自定义损失函数

def customLoss(true, pred) //do_stuff //print(variables) return loss

现在我调用编译为model.compile(optimizer='Adamax', loss = customLoss)

编辑:我尝试了 tf.Print,这是我的结果。

    def customLoss(params):

        def lossFunc(true, pred):
            true = tf.Print(true, [true.shape],'loss-func') #obviously this won't work because the tensors aren't the same shape; however, this is what I want to do.
            #stuff
            return loss
        return lossFunc

    model = Model(inputs=[inputs], outputs=[outputs])
    parallel_model = multi_gpu_model(model, gpus=8)
    parallel_model.compile(opimizer='Adam', loss = customLoss(params), metrics = [mean_iou)
    history = parallel_model.fit(X_train, Y_train, validation_split=0.25, batch_size = 32, verbose=1)

输出是

Epoch 1/10
1159/1159 [==============================] - 75s 65ms/step - loss: 0.1051 - mean_iou: 0.4942 - val_loss: 0.0924 - val_mean_iou: 0.6933
Epoch 2/10
1152/1159 [============================>.] - ETA: 0s - loss: 0.0408 - mean_iou: 0.7608

打印语句仍然没有打印。我错过了什么 - 我的输入tf.Print不正确吗?

标签: pythontensorflowneural-networkkeras

解决方案


这不是因为 Keras 转储缓冲区或做魔术,它根本不调用它们!损失函数被调用一次以构建计算图,然后返回代表损失值的符号张量。Tensorflow 使用它来计算损失、梯度等。

您可能会对tf.Print感兴趣,它是一个带有副作用的空操作,它打印传递的参数。由于tf.Print它是计算图的一部分,因此它也将在训练时运行。从文档中:

打印张量列表。这是一个身份操作(行为类似于 tf.identity),在评估时具有打印数据的副作用。


推荐阅读