From bbab3de8c52dea72c62d1d56dc08cf53dd9ff73e Mon Sep 17 00:00:00 2001 From: Lenakeiz Date: Fri, 13 Mar 2026 23:54:38 +0000 Subject: [PATCH] Fix TensorFlow GradientTape example returning None due to tensor not being watched --- chapter02_mathematical-building-blocks.ipynb | 25 ++++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/chapter02_mathematical-building-blocks.ipynb b/chapter02_mathematical-building-blocks.ipynb index 3c419b7b8..a0a2acbc9 100644 --- a/chapter02_mathematical-building-blocks.ipynb +++ b/chapter02_mathematical-building-blocks.ipynb @@ -6,7 +6,11 @@ "colab_type": "text" }, "source": [ - "This is a companion notebook for the book [Deep Learning with Python, Third Edition](https://www.manning.com/books/deep-learning-with-python-third-edition). For readability, it only contains runnable code blocks and section titles, and omits everything else in the book: text paragraphs, figures, and pseudocode.\n\n**If you want to be able to follow what's going on, I recommend reading the notebook side by side with your copy of the book.**\n\nThe book's contents are available online at [deeplearningwithpython.io](https://deeplearningwithpython.io)." + "This is a companion notebook for the book [Deep Learning with Python, Third Edition](https://www.manning.com/books/deep-learning-with-python-third-edition). For readability, it only contains runnable code blocks and section titles, and omits everything else in the book: text paragraphs, figures, and pseudocode.\n", + "\n", + "**If you want to be able to follow what's going on, I recommend reading the notebook side by side with your copy of the book.**\n", + "\n", + "The book's contents are available online at [deeplearningwithpython.io](https://deeplearningwithpython.io)." ] }, { @@ -1316,17 +1320,28 @@ }, { "cell_type": "code", - "execution_count": 0, + "execution_count": 1, "metadata": { "colab_type": "code" }, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "UsageError: Cell magic `%%backend` not found.\n" + ] + } + ], "source": [ "%%backend tensorflow\n", "import tensorflow as tf\n", "\n", "x = tf.zeros(shape=())\n", "with tf.GradientTape() as tape:\n", + " # Explicitly tell the tape to track x, since tensors created with tf.zeros\n", + " # are not automatically watched (only tf.Variable objects are).\n", + " tape.watch(x)\n", " y = 2 * x + 3\n", "grad_of_y_wrt_x = tape.gradient(y, x)" ] @@ -1449,9 +1464,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.0" + "version": "3.10.11" } }, "nbformat": 4, "nbformat_minor": 0 -} \ No newline at end of file +}