为什么K.gradients对wrt输入的损失梯度不返回



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

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

最新更新