【问题标题】:Loss function provide NAN gradient损失函数提供 NAN 梯度
【发布时间】:2020-08-25 11:35:43
【问题描述】:

我使用直方图损失作为模型的损失函数,但它提供了 NAN 梯度。 代码sn-p(损失函数):

def histogram_loss(y_true, y_pred):
    h_true = tf.histogram_fixed_width( y_true, value_range=(-1., 1.), nbins=20)
    h_pred = tf.histogram_fixed_width( y_pred, value_range=(-1., 1.), nbins=20)
    h_true = tf.cast(h_true, dtype=tf.dtypes.float32)
    h_pred = tf.cast(h_pred, dtype=tf.dtypes.float32)
    return K.mean(K.square(h_true - h_pred))

错误信息:

ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.

为什么会出现值错误(NAN 梯度)?

【问题讨论】:

    标签: python tensorflow keras deep-learning loss-function


    【解决方案1】:

    tf.histogram的梯度是None...不是微分函数

    x = tf.Variable(np.random.uniform(0,10, 100), dtype=tf.float32)
    
    with tf.GradientTape() as tape:
        hist = tf.histogram_fixed_width(x, value_range=(-1., 1.), nbins=20)
        hist = tf.cast(hist, dtype=tf.dtypes.float32)
    
    grads = tape.gradient(hist, x)
    grads
    

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 2021-10-26
      • 2021-07-24
      • 2016-11-29
      • 1970-01-01
      • 2016-07-01
      • 2019-03-20
      • 2019-05-09
      • 1970-01-01
      相关资源
      最近更新 更多