简体   繁体   English

在Keras中调用model.fit时无法从损失函数运行打印语句

[英]unable to run print statements from loss function when calling model.fit in Keras

I have created a custom loss function called 我创建了一个自定义损失函数,名为

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

Now I'm calling compile as model.compile(optimizer='Adamax', loss = customLoss) 现在我称编译为model.compile(optimizer='Adamax', loss = customLoss)

EDIT: I tried tf.Print and this is my result. 编辑:我尝试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)

and the output is 输出是

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

The print statements still aren't printing. 打印语句仍然不打印。 Am I missing something - are my inputs into tf.Print not proper? 我是否缺少某些内容-输入tf.Print输入不正确吗?

It's not because Keras dumps buffers or does magic, it simply doesn't call them! 这并不是因为Keras会转储缓冲区或执行魔术,而是根本不调用它们! The loss function is called once to construct the computation graph and then the symbolic tensor that represents the loss value is returned. 调用一次损失函数以构造计算图 ,然后返回表示损失值的符号张量。 Tensorflow uses that to compute the loss, gradients etc. Tensorflow使用它来计算损耗,梯度等。

You might instead be interested tf.Print that is null operation with a side effect that prints the arguments passed. 您可能反而对tf.Print感兴趣,它是一个空操作,具有打印所传递的参数的副作用。 Since tf.Print is part of the computation graph it will be run when training as well. 由于tf.Print是计算图的一部分,因此也会在训练时运行。 From the documentation: 从文档中:

Prints a list of tensors. 打印张量列表。 This is an identity op (behaves like tf.identity) with the side effect of printing data when evaluating. 这是一个身份操作(与tf.identity相似),具有评估时打印数据的副作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM