【问题标题】:Why does a penalty not change the predictions of a Keras model?为什么惩罚不会改变 Keras 模型的预测?
【发布时间】:2022-01-18 17:07:46
【问题描述】:

我最近在尝试实现自定义损失函数时遇到了这个问题。以下两个损失函数产生完全相同的结果,即使在第二个损失函数返回的结果中添加了一个大的随机值,并确保了 jupyter notebook 中的可重复性。任何想法为什么会这样?


def customLoss1():

  def binary_crossentropy1(y_true, y_pred): 

    bin_cross = tf.keras.losses.BinaryCrossentropy()
    bce = K.mean(bin_cross(y_true, y_pred))

    return bce

  return binary_crossentropy1


def customLoss2():

  def binary_crossentropy2(y_true, y_pred): 

    bin_cross = tf.keras.losses.BinaryCrossentropy()
    bce = K.mean(bin_cross(y_true, y_pred)) + tf.random.normal([], mean=0.0, stddev=10.0)

    return bce

  return binary_crossentropy2

【问题讨论】:

    标签: python tensorflow keras loss-function


    【解决方案1】:

    您的错误一定在其他地方,因为您发布的损失函数确实会产生不同的结果:

    import tensorflow as tf
    tf.random.set_seed(11)
    
    def binary_crossentropy1(y_true, y_pred): 
    
      bin_cross = tf.keras.losses.BinaryCrossentropy(from_logits=True)
      bce = tf.keras.backend.mean(bin_cross(y_true, y_pred))
      return bce
    
    def binary_crossentropy2(y_true, y_pred): 
    
      bin_cross = tf.keras.losses.BinaryCrossentropy(from_logits=True)
      bce = tf.keras.backend.mean(bin_cross(y_true, y_pred)) + tf.random.normal([], mean=0.0, stddev=10.0)
      return bce
    
    y_true = tf.constant([0, 1, 0, 0])
    y_pred = tf.constant([-18.6, 0.51, 2.94, -12.8])
    print(binary_crossentropy1(y_true, y_pred))
    print(binary_crossentropy2(y_true, y_pred))
    
    tf.Tensor(0.865458, shape=(), dtype=float32)
    tf.Tensor(-14.364014, shape=(), dtype=float32)
    

    【讨论】:

    • 你说得对。我将不得不再次查看我的代码并尝试找到错误。谢谢!
    • 我没有发现问题。我尽可能地分解了​​我的代码并写了一个新问题,包括周围的代码。如果你看一看,我将不胜感激。 stackoverflow.com/q/70803497/17700571
    猜你喜欢
    • 2016-10-19
    • 1970-01-01
    • 2021-10-11
    • 2020-04-22
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 2011-07-30
    相关资源
    最近更新 更多