python - 如何计算损失梯度 w.r.t 以模拟 Keras 模型中的输入?

标签 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>

最佳答案

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

关于python - 如何计算损失梯度 w.r.t 以模拟 Keras 模型中的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53649837/

相关文章:

python - 容器 (python) 中的 AWS Lambda 可在本地运行但未部署

python - 在 Django 中自动更新个人资料图片

python - 以 __file__ 作为输入的abspath()

python - 使用tensorflow-gpu进行预测比tensorflow-cpu慢

python - 如何在 Tensorflow Serving 中进行批处理?

python - Scikit-Learn .fit() 方法如何将数据传递给 .predict()?

python - 找不到匹配的表格

python - 如何使用 Tensorflow 的 batch_sequences_with_states 实用程序

r - 神经网络的预测函数给出奇怪的结果

machine-learning - 非二元决策树到二元决策树(机器学习)