model
是我训练的Keras残差模型。我正在尝试计算没有输入张量的损耗的梯度,
tf.gradients(mse(model.predict(x), y), x[0])
(没有输入张量的损耗梯度),给我:
[None].
None
是什么意思,我该如何计算这些梯度?
答案 0 :(得分:0)
要计算梯度,您必须使用符号张量和运算:
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])