model
是我的训练好的 Keras 残差模型。我试图计算损失相对于输入张量的梯度,但是:
tf.gradients(mse(model.predict(x), y), x[0])
(损失相对于输入张量的梯度),返回给我的是:
[None].
这里的 None
是什么意思?我该如何计算这些梯度?
回答:
要计算梯度,你必须使用符号张量和操作:
from keras import backend as Kfrom keras.losses import the_loss_function # 导入合适的损失函数y = Input(shape=labels_shape)# 这是给定某些输入数据时,损失相对于输入的梯度grads = K.gradients(the_loss_function(y, model.output), model.inputs)func = K.function(model.inputs + [y, K.learning_phase()], grads)# 在测试模式下使用 = 0out = func([input_data_array, input_labels_array, 0])# 在训练模式下使用 = 1out = func([input_data_array, input_labels_array, 1])