Keras Custom loss 当实际值和预测值在零的对立面时惩罚更多

Keras Custom loss Penalize more when actual and prediction are on opposite sides of Zero

我正在训练一个模型来预测价格的百分比变化。 MSE 和 RMSE 都给我高达 99% 的准确度,但是当我检查实际和预测指向同一方向的频率时 ((actual >0 and pred > 0) or (actual < 0 and pred < 0)),我得到大约 49%。

请问我如何定义一个非常严重地惩罚相反方向的自定义损失。当预测在给定方向上超过实际时,我还想添加一个轻微的惩罚。

所以

我会留给你来定义你的确切逻辑,但这里是你如何用 tf.cond 实现你想要的:

import tensorflow as tf

y_true = [[0.1]]
y_pred = [[0.05]]
mse = tf.keras.losses.MeanSquaredError()

def custom_loss(y_true, y_pred):
  penalty = 20

  # actual = 0.1 and pred = -0.05 should be penalized a lot more than actual = 0.1 and pred = 0.05
  loss = tf.cond(tf.logical_and(tf.greater(y_true, 0.0), tf.less(y_pred, 0.0)),
                   lambda: mse(y_true, y_pred) * penalty,
                   lambda: mse(y_true, y_pred) * penalty / 4)
  
  #actual = 0.1 and pred = 0.15 slightly more penalty than actual = 0.1 and pred = 0.05
  loss = tf.cond(tf.greater(y_pred, y_true),
                   lambda: loss * penalty / 2,
                   lambda: loss * penalty / 3)
  return loss 
  
print(custom_loss(y_true, y_pred))