tensorflow.gradients gives None value



model是我训练的Keras残差模型。我正试图计算输入张量的损失梯度,然而:

tf.gradients(mse(model.predict(x), y), x[0])

(相对于输入张量的损失梯度(,给我:

[None].

这里的None是什么意思?我如何计算这些梯度?

要计算梯度,必须使用符号张量和运算:

from keras import backend as K
from keras.losses import the_loss_function   # import the suitable loss function
y = Input(shape=labels_shape)
# this is the gradient of loss with respect to inputs given some input data
grads = K.gradients(the_loss_function(y, model.output), model.inputs)
func = K.function(model.inputs + [y, K.learning_phase()], grads)
# usage in test mode = 0
out = func([input_data_array, input_labels_array, 0])
# usage in train mode = 1
out = func([input_data_array, input_labels_array, 1])

最新更新