Keras 中的噪声信号比自定义损失函数不起作用

Noise To Signal Ratio custom loss function in Keras not working

我正在尝试在 Keras 中实现噪声信号比损失函数。我从 this repo 翻译了与 torch 一起使用的代码。 不确定我使用的 tf.math 操作是否与火炬的功能相同。训练时,我不断得到 loss: nan - val_loss: nan。 我究竟做错了什么? 任何帮助表示赞赏。 谢谢

def noiseToSignalLoss(y_true, y_pred):
    losses = tf.math.divide(
        tf.math.reduce_sum(
            tf.math.pow(
                tf.math.abs(
                    tf.math.subtract(
                        y_true,
                        y_pred
                    )
                ),
                2
            ),
            axis=-1
        ),
        tf.math.reduce_sum(
            tf.math.pow(tf.math.abs(y_true),2),
            axis=-1
        )
    )
    return tf.reduce_mean(losses, axis=-1)

我尝试将您的代码应用于某些输入,发现它确实有效。 我认为 nan 的原因是网络的输出(而不是损失函数)。 (例如,输出为 nan 或 y_true 非常接近于零以致除以它会导致 inf。)

似乎 axis 参数有误。这是 Keras 的有效噪声信号比损失函数,如果有人感兴趣的话:

def noiseToSignalLoss(y_true, y_pred):
    losses = tf.math.divide(
        tf.math.reduce_sum(
            tf.math.pow(
                tf.math.abs(
                    tf.math.subtract(
                        y_true,
                        y_pred
                    )
                ),
                2
            )
        ),
        tf.math.reduce_sum(
            tf.math.pow(tf.math.abs(y_true),2)
        )
    )
    return tf.reduce_mean(losses)