{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# Parameter Management\n",
    "\n",
    "Once we have chosen an architecture\n",
    "and set our hyperparameters,\n",
    "we proceed to the training loop,\n",
    "where our goal is to find parameter values\n",
    "that minimize our loss function.\n",
    "After training, we will need these parameters\n",
    "in order to make future predictions.\n",
    "Additionally, we will sometimes wish\n",
    "to extract the parameters\n",
    "either to reuse them in some other context,\n",
    "to save our model to disk so that\n",
    "it may be executed in other software,\n",
    "or for examination in the hope of\n",
    "gaining scientific understanding.\n",
    "\n",
    "Most of the time, we will be able\n",
    "to ignore the nitty-gritty details\n",
    "of how parameters are declared\n",
    "and manipulated, relying on deep learning frameworks\n",
    "to do the heavy lifting.\n",
    "However, when we move away from\n",
    "stacked architectures with standard layers,\n",
    "we will sometimes need to get into the weeds\n",
    "of declaring and manipulating parameters.\n",
    "In this section, we cover the following:\n",
    "\n",
    "* Accessing parameters for debugging, diagnostics, and visualizations.\n",
    "* Parameter initialization.\n",
    "* Sharing parameters across different model components.\n",
    "\n",
    "(**We start by focusing on an MLP with one hidden layer.**)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "origin_pos": 3,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: shape=(2, 1), dtype=float32, numpy=\n",
       "array([[-0.08433171],\n",
       "       [-0.11898197]], dtype=float32)>"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "net = tf.keras.models.Sequential([\n",
    "    tf.keras.layers.Flatten(),\n",
    "    tf.keras.layers.Dense(4, activation=tf.nn.relu),\n",
    "    tf.keras.layers.Dense(1),\n",
    "])\n",
    "\n",
    "X = tf.random.uniform((2, 4))\n",
    "net(X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 4
   },
   "source": [
    "## [**Parameter Access**]\n",
    "\n",
    "Let us start with how to access parameters\n",
    "from the models that you already know.\n",
    "When a model is defined via the `Sequential` class,\n",
    "we can first access any layer by indexing\n",
    "into the model as though it were a list.\n",
    "Each layer's parameters are conveniently\n",
    "located in its attribute.\n",
    "We can inspect the parameters of the second fully-connected layer as follows.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "origin_pos": 7,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[<tf.Variable 'dense_1/kernel:0' shape=(4, 1) dtype=float32, numpy=\n",
      "array([[ 0.6178552 ],\n",
      "       [-0.0967508 ],\n",
      "       [ 0.20512176],\n",
      "       [ 0.94068813]], dtype=float32)>, <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32, numpy=array([0.], dtype=float32)>]\n"
     ]
    }
   ],
   "source": [
    "print(net.layers[2].weights)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 8
   },
   "source": [
    "The output tells us a few important things.\n",
    "First, this fully-connected layer\n",
    "contains two parameters,\n",
    "corresponding to that layer's\n",
    "weights and biases, respectively.\n",
    "Both are stored as single precision floats (float32).\n",
    "Note that the names of the parameters\n",
    "allow us to uniquely identify\n",
    "each layer's parameters,\n",
    "even in a network containing hundreds of layers.\n",
    "\n",
    "\n",
    "### [**Targeted Parameters**]\n",
    "\n",
    "Note that each parameter is represented\n",
    "as an instance of the parameter class.\n",
    "To do anything useful with the parameters,\n",
    "we first need to access the underlying numerical values.\n",
    "There are several ways to do this.\n",
    "Some are simpler while others are more general.\n",
    "The following code extracts the bias\n",
    "from the second neural network layer, which returns a parameter class instance, and \n",
    "further accesses that parameter's value.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "origin_pos": 11,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'>\n",
      "<tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32, numpy=array([0.], dtype=float32)>\n",
      "tf.Tensor([0.], shape=(1,), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "print(type(net.layers[2].weights[1]))\n",
    "print(net.layers[2].weights[1])\n",
    "print(tf.convert_to_tensor(net.layers[2].weights[1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 15
   },
   "source": [
    "### [**All Parameters at Once**]\n",
    "\n",
    "When we need to perform operations on all parameters,\n",
    "accessing them one-by-one can grow tedious.\n",
    "The situation can grow especially unwieldy\n",
    "when we work with more complex blocks (e.g., nested blocks),\n",
    "since we would need to recurse\n",
    "through the entire tree to extract\n",
    "each sub-block's parameters. Below we demonstrate accessing the parameters of the first fully-connected layer vs. accessing all layers.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "origin_pos": 18,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[<tf.Variable 'dense/kernel:0' shape=(4, 4) dtype=float32, numpy=\n",
      "array([[-0.79512775,  0.83131605, -0.46970606, -0.386196  ],\n",
      "       [-0.23707926,  0.58012336, -0.4286804 ,  0.80075485],\n",
      "       [-0.16268367,  0.3944226 , -0.3487624 , -0.7027458 ],\n",
      "       [-0.56425023, -0.02344972,  0.5696172 , -0.53518283]],\n",
      "      dtype=float32)>, <tf.Variable 'dense/bias:0' shape=(4,) dtype=float32, numpy=array([0., 0., 0., 0.], dtype=float32)>]\n",
      "[array([[-0.79512775,  0.83131605, -0.46970606, -0.386196  ],\n",
      "       [-0.23707926,  0.58012336, -0.4286804 ,  0.80075485],\n",
      "       [-0.16268367,  0.3944226 , -0.3487624 , -0.7027458 ],\n",
      "       [-0.56425023, -0.02344972,  0.5696172 , -0.53518283]],\n",
      "      dtype=float32), array([0., 0., 0., 0.], dtype=float32), array([[ 0.6178552 ],\n",
      "       [-0.0967508 ],\n",
      "       [ 0.20512176],\n",
      "       [ 0.94068813]], dtype=float32), array([0.], dtype=float32)]\n"
     ]
    }
   ],
   "source": [
    "print(net.layers[1].weights)\n",
    "print(net.get_weights())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 19
   },
   "source": [
    "This provides us with another way of accessing the parameters of the network as follows.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "origin_pos": 22,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0., 0., 0., 0.], dtype=float32)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net.get_weights()[1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 23
   },
   "source": [
    "### [**Collecting Parameters from Nested Blocks**]\n",
    "\n",
    "Let us see how the parameter naming conventions work\n",
    "if we nest multiple blocks inside each other.\n",
    "For that we first define a function that produces blocks\n",
    "(a block factory, so to speak) and then\n",
    "combine these inside yet larger blocks.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "origin_pos": 26,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: shape=(2, 1), dtype=float32, numpy=\n",
       "array([[1.0394679e-01],\n",
       "       [5.4984648e-06]], dtype=float32)>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def block1(name):\n",
    "    return tf.keras.Sequential([\n",
    "        tf.keras.layers.Flatten(),\n",
    "        tf.keras.layers.Dense(4, activation=tf.nn.relu)],\n",
    "        name=name)\n",
    "\n",
    "def block2():\n",
    "    net = tf.keras.Sequential()\n",
    "    for i in range(4):\n",
    "        # Nested here\n",
    "        net.add(block1(name=f'block-{i}'))\n",
    "    return net\n",
    "\n",
    "rgnet = tf.keras.Sequential()\n",
    "rgnet.add(block2())\n",
    "rgnet.add(tf.keras.layers.Dense(1))\n",
    "rgnet(X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 27
   },
   "source": [
    "Now that [**we have designed the network,\n",
    "let us see how it is organized.**]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "origin_pos": 30,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential_1\"\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "_________________________________________________________________\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Layer (type)                Output Shape              Param #   \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=================================================================\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " sequential_2 (Sequential)   (2, 4)                    80        \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                                                                 \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " dense_6 (Dense)             (2, 1)                    5         \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                                                                 \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=================================================================\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total params: 85\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Trainable params: 85\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Non-trainable params: 0\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "_________________________________________________________________\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "source": [
    "print(rgnet.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 31
   },
   "source": [
    "Since the layers are hierarchically nested,\n",
    "we can also access them as though\n",
    "indexing through nested lists.\n",
    "For instance, we can access the first major block,\n",
    "within it the second sub-block,\n",
    "and within that the bias of the first layer,\n",
    "with as follows.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "origin_pos": 34,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Variable 'dense_3/bias:0' shape=(4,) dtype=float32, numpy=array([0., 0., 0., 0.], dtype=float32)>"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rgnet.layers[0].layers[1].layers[1].weights[1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 35
   },
   "source": [
    "## Parameter Initialization\n",
    "\n",
    "Now that we know how to access the parameters,\n",
    "let us look at how to initialize them properly.\n",
    "We discussed the need for proper initialization in :numref:`sec_numerical_stability`.\n",
    "The deep learning framework provides default random initializations to its layers.\n",
    "However, we often want to initialize our weights\n",
    "according to various other protocols. The framework provides most commonly\n",
    "used protocols, and also allows to create a custom initializer.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 38,
    "tab": [
     "tensorflow"
    ]
   },
   "source": [
    "By default, Keras initializes weight matrices uniformly by drawing from a range that is computed according to the input and output dimension, and the bias parameters are all set to zero.\n",
    "TensorFlow provides a variety of initialization methods both in the root module and the `keras.initializers` module.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 39
   },
   "source": [
    "### [**Built-in Initialization**]\n",
    "\n",
    "Let us begin by calling on built-in initializers.\n",
    "The code below initializes all weight parameters\n",
    "as Gaussian random variables\n",
    "with standard deviation 0.01, while bias parameters cleared to zero.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "origin_pos": 42,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(<tf.Variable 'dense_7/kernel:0' shape=(4, 4) dtype=float32, numpy=\n",
       " array([[ 0.00066365,  0.00333936,  0.01477699,  0.00209371],\n",
       "        [ 0.00958354,  0.00777195,  0.0079657 , -0.01103103],\n",
       "        [ 0.00491197, -0.00057486, -0.00377766,  0.01107858],\n",
       "        [-0.0099234 ,  0.00970089,  0.00464214, -0.02127186]],\n",
       "       dtype=float32)>,\n",
       " <tf.Variable 'dense_7/bias:0' shape=(4,) dtype=float32, numpy=array([0., 0., 0., 0.], dtype=float32)>)"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net = tf.keras.models.Sequential([\n",
    "    tf.keras.layers.Flatten(),\n",
    "    tf.keras.layers.Dense(\n",
    "        4, activation=tf.nn.relu,\n",
    "        kernel_initializer=tf.random_normal_initializer(mean=0, stddev=0.01),\n",
    "        bias_initializer=tf.zeros_initializer()),\n",
    "    tf.keras.layers.Dense(1)])\n",
    "\n",
    "net(X)\n",
    "net.weights[0], net.weights[1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 43
   },
   "source": [
    "We can also initialize all the parameters\n",
    "to a given constant value (say, 1).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "origin_pos": 46,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(<tf.Variable 'dense_9/kernel:0' shape=(4, 4) dtype=float32, numpy=\n",
       " array([[1., 1., 1., 1.],\n",
       "        [1., 1., 1., 1.],\n",
       "        [1., 1., 1., 1.],\n",
       "        [1., 1., 1., 1.]], dtype=float32)>,\n",
       " <tf.Variable 'dense_9/bias:0' shape=(4,) dtype=float32, numpy=array([0., 0., 0., 0.], dtype=float32)>)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net = tf.keras.models.Sequential([\n",
    "    tf.keras.layers.Flatten(),\n",
    "    tf.keras.layers.Dense(\n",
    "        4, activation=tf.nn.relu,\n",
    "        kernel_initializer=tf.keras.initializers.Constant(1),\n",
    "        bias_initializer=tf.zeros_initializer()),\n",
    "    tf.keras.layers.Dense(1),\n",
    "])\n",
    "\n",
    "net(X)\n",
    "net.weights[0], net.weights[1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 47
   },
   "source": [
    "[**We can also apply different initializers for certain blocks.**]\n",
    "For example, below we initialize the first layer\n",
    "with the Xavier initializer\n",
    "and initialize the second layer\n",
    "to a constant value of 42.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "origin_pos": 50,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<tf.Variable 'dense_11/kernel:0' shape=(4, 4) dtype=float32, numpy=\n",
      "array([[-0.73864233, -0.6834252 , -0.71073395, -0.33731312],\n",
      "       [ 0.6014491 , -0.06163079, -0.25806284,  0.49404734],\n",
      "       [ 0.08400023,  0.38193828, -0.38312507, -0.51248205],\n",
      "       [-0.76102585, -0.7137217 , -0.06061447, -0.1622476 ]],\n",
      "      dtype=float32)>\n",
      "<tf.Variable 'dense_12/kernel:0' shape=(4, 1) dtype=float32, numpy=\n",
      "array([[42.],\n",
      "       [42.],\n",
      "       [42.],\n",
      "       [42.]], dtype=float32)>\n"
     ]
    }
   ],
   "source": [
    "net = tf.keras.models.Sequential([\n",
    "    tf.keras.layers.Flatten(),\n",
    "    tf.keras.layers.Dense(\n",
    "        4,\n",
    "        activation=tf.nn.relu,\n",
    "        kernel_initializer=tf.keras.initializers.GlorotUniform()),\n",
    "    tf.keras.layers.Dense(\n",
    "        1, kernel_initializer=tf.keras.initializers.Constant(42)),\n",
    "])\n",
    "\n",
    "net(X)\n",
    "print(net.layers[1].weights[0])\n",
    "print(net.layers[2].weights[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 51
   },
   "source": [
    "### [**Custom Initialization**]\n",
    "\n",
    "Sometimes, the initialization methods we need\n",
    "are not provided by the deep learning framework.\n",
    "In the example below, we define an initializer\n",
    "for any weight parameter $w$ using the following strange distribution:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "    w \\sim \\begin{cases}\n",
    "        U(5, 10) & \\text{ with probability } \\frac{1}{4} \\\\\n",
    "            0    & \\text{ with probability } \\frac{1}{2} \\\\\n",
    "        U(-10, -5) & \\text{ with probability } \\frac{1}{4}\n",
    "    \\end{cases}\n",
    "\\end{aligned}\n",
    "$$\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 54,
    "tab": [
     "tensorflow"
    ]
   },
   "source": [
    "Here we define a subclass of `Initializer` and implement the `__call__`\n",
    "function that return a desired tensor given the shape and data type.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "origin_pos": 57,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<tf.Variable 'dense_13/kernel:0' shape=(4, 4) dtype=float32, numpy=\n",
      "array([[ 6.7411003, -6.69713  ,  0.       ,  9.420845 ],\n",
      "       [ 7.424906 , -6.1664796,  0.       ,  0.       ],\n",
      "       [ 0.       , -0.       , -5.791514 ,  0.       ],\n",
      "       [ 0.       ,  9.827469 ,  0.       , -0.       ]], dtype=float32)>\n"
     ]
    }
   ],
   "source": [
    "class MyInit(tf.keras.initializers.Initializer):\n",
    "    def __call__(self, shape, dtype=None):\n",
    "        data=tf.random.uniform(shape, -10, 10, dtype=dtype)\n",
    "        factor=(tf.abs(data) >= 5)\n",
    "        factor=tf.cast(factor, tf.float32)\n",
    "        return data * factor\n",
    "\n",
    "net = tf.keras.models.Sequential([\n",
    "    tf.keras.layers.Flatten(),\n",
    "    tf.keras.layers.Dense(\n",
    "        4,\n",
    "        activation=tf.nn.relu,\n",
    "        kernel_initializer=MyInit()),\n",
    "    tf.keras.layers.Dense(1),\n",
    "])\n",
    "\n",
    "net(X)\n",
    "print(net.layers[1].weights[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 58
   },
   "source": [
    "Note that we always have the option\n",
    "of setting parameters directly.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "origin_pos": 61,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Variable 'dense_13/kernel:0' shape=(4, 4) dtype=float32, numpy=\n",
       "array([[42.       , -5.69713  ,  1.       , 10.420845 ],\n",
       "       [ 8.424906 , -5.1664796,  1.       ,  1.       ],\n",
       "       [ 1.       ,  1.       , -4.791514 ,  1.       ],\n",
       "       [ 1.       , 10.827469 ,  1.       ,  1.       ]], dtype=float32)>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net.layers[1].weights[0][:].assign(net.layers[1].weights[0] + 1)\n",
    "net.layers[1].weights[0][0, 0].assign(42)\n",
    "net.layers[1].weights[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 63
   },
   "source": [
    "## [**Tied Parameters**]\n",
    "\n",
    "Often, we want to share parameters across multiple layers.\n",
    "Let us see how to do this elegantly.\n",
    "In the following we allocate a dense layer\n",
    "and then use its parameters specifically\n",
    "to set those of another layer.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "origin_pos": 66,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "# tf.keras behaves a bit differently. It removes the duplicate layer\n",
    "# automatically\n",
    "shared = tf.keras.layers.Dense(4, activation=tf.nn.relu)\n",
    "net = tf.keras.models.Sequential([\n",
    "    tf.keras.layers.Flatten(),\n",
    "    shared,\n",
    "    shared,\n",
    "    tf.keras.layers.Dense(1),\n",
    "])\n",
    "\n",
    "net(X)\n",
    "# Check whether the parameters are different\n",
    "print(len(net.layers) == 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 68
   },
   "source": [
    "## Summary\n",
    "\n",
    "* We have several ways to access, initialize, and tie model parameters.\n",
    "* We can use custom initialization.\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Use the `FancyMLP` model defined in :numref:`sec_model_construction` and access the parameters of the various layers.\n",
    "1. Look at the initialization module document to explore different initializers.\n",
    "1. Construct an MLP containing a shared parameter layer and train it. During the training process, observe the model parameters and gradients of each layer.\n",
    "1. Why is sharing parameters a good idea?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 71,
    "tab": [
     "tensorflow"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/269)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}