【问题标题】:Why is K.gradients is returning none for gradient of loss wrt input为什么 K.gradients 对于输入的损失梯度没有返回任何值
【发布时间】:2020-04-17 08:55:53
【问题描述】:

我想知道为什么我的毕业生在以下代码中没有得到任何信息:

import tensorflow.keras.losses as losses
loss = losses.squared_hinge(y_true, y_pred)

from tensorflow.keras import backend as K
grads = K.gradients(loss, CNN_model.input)[0]
iterate = K.function([CNN_model.input], [loss, grads])

我的 CNN_model.input 是: <tf.Tensor 'conv2d_3_input:0' shape=(?, 28, 28, 1) dtype=float32>

我的损失是: <tf.Tensor 'Mean_3:0' shape=(1,) dtype=float64>

注意:如果这很重要,我会将 SVM 的预测输出作为 y_pred 传递给我的应用程序。

【问题讨论】:

    标签: tensorflow machine-learning keras


    【解决方案1】:

    据我之前的经验了解,Tensorflow 需要使用GradientTape 来记录某个变量的活动并计算其梯度。在你的情况下应该是这样的:

    x = np.random.rand(10) #your input variable
    x = tf.Variable(x) #to be evaluated by GradientTape the input should be a tensor
    with tf.GradientTape() as tape:
        tape.watch(x) #with this method you can observe your variable
        proba = model(x) #get the prediction of the input
        loss = your_loss_function(y_true, proba) #compute the loss
    
    gradient = tape.gradient(loss, x) #compute the gradients, this must be done outside the recording
    

    【讨论】:

    • 在 tensorflow 1 中可以使用渐变胶带吗?
    • @MangLion 它也应该出现在 Tensorflow 1 中。不幸的是我不确定,所以必须对其进行验证。
    • 无论如何,这非常有用,谢谢。最后一件事,只是为了确认。在您的示例中,您计算​​了输入的梯度,对吗?
    • @MangLion 是的,当然!你可以看到,因为我使用了输入的预测来计算损失。
    • 您好,我还有另一个问题与切换到此方法后获取 None 的问题有关,您可能有兴趣在此处发布:stackoverflow.com/questions/61367182/… 如果没有,请不要担心。
    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 2021-05-08
    • 1970-01-01
    相关资源
    最近更新 更多