【问题标题】:tensorflow.gradients gives None valuetensorflow.gradients 给出 None 值
【发布时间】:2018-12-19 14:31:23
【问题描述】:

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

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

(输入张量的损失梯度),给我:

[None].

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

【问题讨论】:

  • 这意味着没有梯度,要获得梯度,您需要充分使用 TensorFlow 符号运算才能使其工作(所以没有 model.predict)。

标签: python tensorflow machine-learning keras gradient


【解决方案1】:

要计算梯度,您必须使用符号张量和运算:

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

【讨论】:

  • 谢谢!不幸的是,当我这样做时,我得到一个 InvalidArgumentError: InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'major_bn/keras_learning_phase' with dtype bool [[node major_bn/keras_learning_phase (defined at /home/ayush99/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:120) = Placeholder[dtype=DT_BOOL, shape=<unknown>, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
  • @AyushShridhar 在函数定义中使用K.learning_phase(),并在使用函数时向其传递值。我已经更新了我的答案。
  • 非常感谢。我实际上是在尝试对我的神经网络实施 FGSM 攻击。但是我尝试了上述方法来实施攻击,但我没有成功欺骗网络。知道可能出了什么问题吗?
  • @AyushShridhar 老实说,没有。我没有处理过这种攻击。您可以提出一个新问题并包含您的代码(相关部分),然后更熟悉该主题的人将能够提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-04
  • 2017-05-11
相关资源
最近更新 更多