tensorflow.gradients给出None值

时间:2018-12-19 14:31:23

标签: python tensorflow machine-learning keras gradient

model是我训练的Keras残差模型。我正在尝试计算没有输入张量的损耗的梯度,

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

(没有输入张量的损耗梯度),给我:

[None].

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

1 个答案:

答案 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])