LogCosh 自定义损失函数返回 nan

问题描述 投票:0回答:2

我正在尝试将 LogCosh 函数实现为自定义损失函数。当我这样做时,我收到一个错误,因为拟合阶段的损失为 NaN。更奇怪的是,当我运行它一堆时,它开始给出损失的实际值,然后到达一个点,它开始再次返回 NaN。

我的型号:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(81,)),
    tf.keras.layers.Dense(300, activation='relu'),
    tf.keras.layers.Dense(1)
])

我的损失函数和数据拟合:

def custom_loss(y_true, y_pred):
    x = y_true-y_pred
    return tf.math.log(tf.math.cosh(x))

model.compile(optimizer='adam',
              loss=custom_loss,
              metrics=['MeanAbsoluteError'])

model.fit(train_features, train_labels, epochs=3)

这给出了

NaN

Train on 21263 samples
Epoch 1/3
21263/21263 [==============================] - 1s 65us/sample - loss: nan - MeanAbsoluteError: nan
Epoch 2/3
21263/21263 [==============================] - 1s 51us/sample - loss: nan - MeanAbsoluteError: nan
Epoch 3/3
21263/21263 [==============================] - 1s 57us/sample - loss: nan - MeanAbsoluteError: nan

为什么它是垃圾/我该如何解决这个问题以便损失真正起作用?

tensorflow keras tensorflow2.0 loss-function
2个回答
1
投票

您不需要为此编写任何自定义函数。

LogCosh
已经是
TF 2.4
中可用的内置损失函数。

model.compile(optimizer='adam',
              loss=tf.keras.losses.LogCosh(),
              metrics=['MeanAbsoluteError'])

0
投票

你可以这样使用它:

tf.math.softplus(-2.0 * x) - tf.cast(tf.math.log(2.0), x.dtype)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.