From ab79e31e7b22ddcb41a9e34462b76f7d9af848ca Mon Sep 17 00:00:00 2001 From: vishnoi246 Date: Tue, 7 Oct 2025 01:06:41 +0530 Subject: [PATCH] Update MyDense example to use self.add_weight() for proper variable tracking Fix: Update custom layer example to use self.add_weight() Problem: The previous MyDense layer created weights with tf.Variable in __init__. These weights were not automatically registered, so layer.variables and layer.trainable_variables were empty. This breaks standard Keras functionality for training, saving, and inspection. Solution: Updated MyDense to use self.add_weight(), which properly registers the weights with the layer. Now they appear in .variables and are fully tracked by Keras. --- site/en/guide/intro_to_modules.ipynb | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/site/en/guide/intro_to_modules.ipynb b/site/en/guide/intro_to_modules.ipynb index 79bbe89ca56..1d329c5d175 100644 --- a/site/en/guide/intro_to_modules.ipynb +++ b/site/en/guide/intro_to_modules.ipynb @@ -748,9 +748,18 @@ " super().__init__(**kwargs)\n", "\n", " # This will soon move to the build step; see below\n", - " self.w = tf.Variable(\n", - " tf.random.normal([in_features, out_features]), name='w')\n", - " self.b = tf.Variable(tf.zeros([out_features]), name='b')\n", + " self.w = self.add_weight( + shape=(in_features, out_features), + initializer="random_normal", + trainable=True, + name="w" + ) + self.b = self.add_weight( + shape=(out_features,), + initializer="zeros", + trainable=True, + name="b" + ) " def call(self, x):\n", " y = tf.matmul(x, self.w) + self.b\n", " return tf.nn.relu(y)\n",