From 3c374704451e64f90d2614efb0cb1fb3aaffdaa1 Mon Sep 17 00:00:00 2001 From: Hsien-Ching Chung Date: Wed, 8 Apr 2026 17:34:14 +0800 Subject: [PATCH] Better example code for the subsection "1. Replaced a variable with a tensor" # Better example code for the subsection "1. Replaced a variable with a tensor" **Position:** "1. Replaced a variable with a tensor" subsection **Link:** https://www.tensorflow.org/guide/autodiff#1_replaced_a_variable_with_a_tensor **Condition:** The original example is very concise. However, it took me a considerable amount of time to modify the code and test it to understand the example fully. I think there are two points that confused me. Point 1: The derivative of `y = x + 1` is a constant scalar `1`. This will cause no value change as the number of epoch increases. We can't obviously see the change in the value. Point 2: The comment directly gives the correct code `# This should be x.assign_add(1)` without the reason. **Suggestion:** I have modified the example code as shown below. 1. The formula has been changed from `y = x + 1` to `y = x**2`. The derivative is now `2x`, and we can obviously see the value change corresponding to epoch. 2. A comment "The `tf.Variable` has been inadvertently replaced with a `tf.Tensor`." has been added. 3. A epoch indicator is added. `print("epoch:", epoch)` 4. The number of epoch is changed from 2 to 3. REF: https://github.com/HsienChing/ML_DL_project_State_Estimation_of_Li-ion_Batteries/blob/main/other/Issues_in_TensorFlow_official_doc_Introduction_to_gradients_and_automatic_differentiation.ipynb --- site/en/guide/autodiff.ipynb | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/site/en/guide/autodiff.ipynb b/site/en/guide/autodiff.ipynb index 237a224569..e07f4450a1 100644 --- a/site/en/guide/autodiff.ipynb +++ b/site/en/guide/autodiff.ipynb @@ -799,12 +799,14 @@ "source": [ "x = tf.Variable(2.0)\n", "\n", - "for epoch in range(2):\n", + "for epoch in range(3):\n", " with tf.GradientTape() as tape:\n", - " y = x+1\n", + " y = x**2\n", "\n", + " print("epoch:", epoch)\n, " print(type(x).__name__, \":\", tape.gradient(y, x))\n", - " x = x + 1 # This should be `x.assign_add(1)`" + " x = x + 1 # The `tf.Variable` has been inadvertently replaced with a `tf.Tensor`." + " # This should be `x.assign_add(1)`." ] }, {