gpt4 book ai didi

tensorflow - 为什么 K.gradients 对于损失 wrt 输入的梯度没有返回

转载 作者:行者123 更新时间:2023-12-04 10:12:30 24 4
gpt4 key购买 nike

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

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需要使用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 - 为什么 K.gradients 对于损失 wrt 输入的梯度没有返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61261285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com