Code Explanation:
1. Import TensorFlow
import tensorflow as tf
You're importing TensorFlow — a deep learning framework used for tensors, models, training, and automatic differentiation.
2. Define Variable x
x = tf.Variable(3.0)
You define a TensorFlow variable x with a float value 3.0.
tf.Variable is used when you want to compute gradients with respect to this variable.
3. Start Recording with GradientTape
with tf.GradientTape() as tape:
y = x**2
tf.GradientTape() is used to record operations for automatic differentiation.
Inside the with block, TensorFlow tracks all computations involving x.
y = x**2 → this is the function whose gradient you want.
4. Compute Gradient
grad = tape.gradient(y, x)
This line computes the gradient of y with respect to x.
5. Print Result
print(grad)
This prints:
tf.Tensor(6.0, shape=(), dtype=float32)
Final Output:
6.0
0 Comments:
Post a Comment