When you are using tf.GradientTape() to compute derivative in tensorflow, you may get this error: AttributeError: ‘RefVariable’ object has no attribute ‘_id’. In this tutorial, we will introduce you how to fix it.
Look at this example:
import tensorflow as tf x = tf.Variable(tf.random_uniform([3,1], -0.01, 0.01)) w = tf.Variable(tf.random_uniform([3,3], -0.01, 0.01)) with tf.GradientTape() as tape: f = tf.matmul(w,x) grad2 = tape.gradient(f,[x]) print(w) print(grad2)
We will run this example code in tensorflow 1.10.
You will get this result:
How to fix this AttributeError?
tf.GradientTape() should be run in tensorflow eager mode, if you are using tensorflow 2.0, you may will not find this error. However, if you are using tensorflow 1.* version, you can fix it as follows:
import tensorflow as tf tf.enable_eager_execution()
We use tf.enable_eager_execution() to make tensorflow run in eager mode. Then run this example again, we can find this AttributeError is fixed.