Python 如何计算Keras模型输入的损失梯度w.r.t?

Python 如何计算Keras模型输入的损失梯度w.r.t?,python,tensorflow,machine-learning,keras,neural-network,Python,Tensorflow,Machine Learning,Keras,Neural Network,我想要实现的是计算交叉熵相对于输入值的梯度x。在TensorFlow中,我对此没有任何问题: ce_grad = tf.gradients(cross_entropy, x) 但随着我的网络越来越大,我转而使用Keras来更快地构建它们。然而,现在我真的不知道如何实现上述目标?有没有办法从存储整个模型的模型变量中提取交叉熵和输入张量 为了清楚起见,我的交叉熵是: cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_lo

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

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

为了清楚起见,我的交叉熵是:

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

我们可以编写一个后端函数来实现这一点。我们使用
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])

谢谢,今天。标签的形状到底是什么?在我的例子中,我有
model.output
:所以我给出了
shape=(10,)
,但是它抛出了一些类型错误:类型错误:当单个张量expected@A.Newski模型的输出形状。例如,对于MNIST数据集上的分类模型,它可能是
(10,)
@A.Newski噢,对不起,我犯了一个小错误。在
K.gradients
中,它必须是
model.inputs
而不是
[model.inputs]
,因为
model.inputs
本身已经是一个列表。我在回答中纠正了这一点。对于
K.function
,也是一样。那么它不应该是
grad\u ce=K.gradients(ce,model.inputs)
?完美的时机:)谢谢!如果答案解决了您的问题,请单击复选标记接受答案(✔) 在答案旁边将其标记为“已回答”-请参阅
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])