如何计算Keras模型中输入模型的损耗梯度?

时间:2018-12-06 10:55:25

标签: python tensorflow machine-learning keras neural-network

我想要实现的是计算相对于输入值x的交叉熵的梯度。在TensorFlow中我对此没有任何麻烦:

ce_grad = tf.gradients(cross_entropy, x)

但是随着我的网络越来越大,我转而使用Keras来更快地建立它们。但是,现在我真的不知道如何实现上述目标?有没有办法从存储整个模型的model变量中提取交叉熵和输入张量?

为清楚起见,我的cross_entropy是:

cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits=y_conv))
<tf.Tensor 'Mean:0' shape=() dtype=float32>

x

x = tf.placeholder(tf.float32, shape = [None,784])
<tf.Tensor 'Placeholder:0' shape=(?, 784) dtype=float32>

1 个答案:

答案 0 :(得分:1)

我们可以编写一个后端函数来做到这一点。我们使用K.categorical_crossentropy来计算损耗,并使用K.gradients来计算其相对于模型输入的梯度:

from keras import backend as K

# an input layer to feed labels
y_true = Input(shape=labels_shape)
# compute loss based on model's output and true labels
ce = K.mean(K.categorical_crossentropy(y_true, model.output))
# compute gradient of loss with respect to inputs
grad_ce = K.gradients(ce, model.inputs)
# create a function to be able to run this computation graph
func = K.function(model.inputs + [y_true], grad_ce)

# usage
output = func([model_input_array(s), true_labels])
相关问题