tensorflow.gradients 给出 None 值
tensorflow.gradients gives None value
model
是我训练好的 Keras 残差模型。我正在尝试计算损失的梯度 w.r.t 输入张量,但是:
tf.gradients(mse(model.predict(x), y), x[0])
(损失梯度 w.r.t 输入张量),给我:
[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])
model
是我训练好的 Keras 残差模型。我正在尝试计算损失的梯度 w.r.t 输入张量,但是:
tf.gradients(mse(model.predict(x), y), x[0])
(损失梯度 w.r.t 输入张量),给我:
[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])