简体   繁体   English

Tensorflow 训练 - 打印一个 output 的多个损失

[英]Tensorflow training - print multiple losses for one output

I would like to print all the different losses I have for one output separately.我想分别打印一个 output 的所有不同损失。 At the moment it looks like:目前它看起来像:

1/1 [==============================] - 1s 1s/sample - loss: 4.2632

The goal is to have a history like:目标是拥有如下历史:

1/1 [==============================] - 1s 1s/sample - loss1: 2.1, loss2: 2.1632

I have one output layer out1 and two loss functions loss1 and loss2.我有一个 output 层 out1 和两个损失函数 loss1 和 loss2。

def loss1(y_true, y_pred):
    ...
    return ...
def loss2(y_true, y_pred):
    ...
    return ...

When I do当我做

model.compile(...)

I can either choose to have a single loss function,我可以选择单损function,

model.compile(loss=lambda x: loss1(x) + loss2(x))

or defining a loss for each output in a dictionary或为字典中的每个 output 定义损失

model.compile(loss={'out1': loss1(x), 'out2': loss2(x)})

Since I have only one output, this isn't an option for me.因为我只有一个 output,所以这不是我的选择。 Does anyone know how to print the losses separately when having only one output?有谁知道只有一个 output 时如何单独打印损失?

Just use the metrics argument:只需使用metrics参数:

model.compile(optimizer='adam', loss='mae', metrics=['mse'])

You will still need to choose one loss to minimize.您仍然需要选择一种损失来最小化。

One workaround is to artificially create the same two outputs, and then combine them with weights equal 1. For the sake of concreteness, I wrote the example:一种解决方法是人为地创建相同的两个输出,然后将它们与等于 1 的权重组合。为了具体起见,我编写了示例:

from tensorflow.keras import Model
from tensorflow.keras.layers import Input, Dense, Lambda
from tensorflow.keras.losses import mse, mae
import numpy as np

if __name__ == '__main__':
    train_x = np.random.rand(10000, 200)
    train_y = np.random.rand(10000, 1)

    x_input = Input(shape=(200))
    x = Dense(64)(x_input)
    x = Dense(64)(x)
    x = Dense(1)(x)

    x1 = Lambda(lambda x: x, name='out1')(x)
    x2 = Lambda(lambda x: x, name='out2')(x)

    model = Model(inputs=x_input, outputs=[x1, x2])

    model.compile(optimizer='adam', loss={'out1': mse, 'out2': mae}, loss_weights={'out1': 1, 'out2': 1})

    model.fit(train_x, train_y, epochs=10)

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

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