How do I get the gradient of a keras model with respect to its inputs?

后端 未结 1 812
独厮守ぢ
独厮守ぢ 2021-01-21 01:08

I just asked a question on the same topic but for custom models (How do I find the derivative of a custom model in Keras?) but realised quickly that this was trying to run befor

相关标签:
1条回答
  • 2021-01-21 01:41

    I ended up getting this to work with a variant of the answer to this question: Get Gradients with Keras Tensorflow 2.0

    x_tensor = tf.convert_to_tensor(input_data, dtype=tf.float32)
    with tf.GradientTape() as t:
        t.watch(x_tensor)
        output = model(x_tensor)
    
    result = output
    gradients = t.gradient(output, x_tensor)
    

    This allows me to obtain both the output and the gradient without redundant computation.

    0 讨论(0)
提交回复
热议问题