{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "execute:\n",
    "  enabled: false\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=linear-regression-scratch-md-1 fw=all -->\n",
    "\n",
    "# Linear Regression Implementation from Scratch\n",
    "\n",
    "We are now ready to work through \n",
    "a fully functioning implementation \n",
    "of linear regression. \n",
    "In this section, \n",
    "we will implement the entire method from scratch,\n",
    "including (i) the model; (ii) the loss function;\n",
    "(iii) a minibatch stochastic gradient descent optimizer;\n",
    "and (iv) the training function \n",
    "that stitches all of these pieces together.\n",
    "Finally, we will run our synthetic data generator\n",
    "from that section\n",
    "and apply our model\n",
    "on the resulting dataset. \n",
    "While modern deep learning frameworks \n",
    "can automate nearly all of this work,\n",
    "implementing things from scratch is the only way\n",
    "to make sure that you really know what you are doing.\n",
    "Moreover, when it is time to customize models,\n",
    "defining our own layers or loss functions,\n",
    "understanding how things work under the hood will prove handy.\n",
    "In this section, we will rely only \n",
    "on tensors and automatic differentiation.\n",
    "Later, we will introduce a more concise implementation,\n",
    "taking advantage of the bells and whistles of deep learning frameworks \n",
    "while retaining the structure of what follows below."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "linear-regression-scratch-linear-regression-implementation-from-scratch"
   },
   "source": [
    "%matplotlib inline\n",
    "from d2l import mxnet as d2l\n",
    "from mxnet import autograd, np, npx\n",
    "npx.set_np()"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=linear-regression-scratch-md-2 fw=all -->\n",
    "\n",
    "## Defining the Model\n",
    "\n",
    "Before we can begin optimizing our model's parameters by minibatch SGD,\n",
    "we need to have some parameters in the first place.\n",
    "In the following we initialize weights by drawing\n",
    "random numbers from a normal distribution with mean 0\n",
    "and a standard deviation of 0.01. \n",
    "The magic number 0.01 often works well in practice, \n",
    "but you can specify a different value \n",
    "through the argument `sigma`.\n",
    "Moreover we set the bias to 0.\n",
    "Note that for object-oriented design\n",
    "we add the code to the `__init__` method of a subclass of `d2l.Module` (introduced in that section)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "linear-regression-scratch-defining-the-model-1"
   },
   "source": [
    "class LinearRegressionScratch(d2l.Module):\n",
    "    \"\"\"The linear regression model implemented from scratch.\"\"\"\n",
    "    def __init__(self, num_inputs, lr, sigma=0.01):\n",
    "        super().__init__()\n",
    "        self.save_hyperparameters()\n",
    "        self.w = d2l.normal(0, sigma, (num_inputs, 1))\n",
    "        self.b = d2l.zeros(1)\n",
    "        self.w.attach_grad()\n",
    "        self.b.attach_grad()"
   ],
   "execution_count": 2,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=linear-regression-scratch-md-3 fw=all -->\n",
    "\n",
    "Next we must define our model,\n",
    "relating its input and parameters to its output.\n",
    "Using the same notation as the equation\n",
    "for our linear model we simply take the matrix--vector product\n",
    "of the input features $\\mathbf{X}$ \n",
    "and the model weights $\\mathbf{w}$,\n",
    "and add the offset $b$ to each example.\n",
    "The product $\\mathbf{Xw}$ is a vector and $b$ is a scalar.\n",
    "Because of the broadcasting mechanism \n",
    "(see that section),\n",
    "when we add a vector and a scalar,\n",
    "the scalar is added to each component of the vector.\n",
    "The resulting `forward` method \n",
    "is registered in the `LinearRegressionScratch` class\n",
    "via `add_to_class` (introduced in that section)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "linear-regression-scratch-defining-the-model-2"
   },
   "source": [
    "@d2l.add_to_class(LinearRegressionScratch)\n",
    "def forward(self, X):\n",
    "    return d2l.matmul(X, self.w) + self.b"
   ],
   "execution_count": 3,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=linear-regression-scratch-md-4 fw=all -->\n",
    "\n",
    "## Defining the Loss Function\n",
    "\n",
    "Since updating our model requires taking\n",
    "the gradient of our loss function,\n",
    "we ought to define the loss function first.\n",
    "Here we use the squared loss function\n",
    "in the equation.\n",
    "Our synthetic data loader already yields labels `y`\n",
    "with the same shape as the predictions `y_hat`\n",
    "(both are $(B, 1)$ column vectors for a batch of size $B$),\n",
    "so we can subtract them elementwise directly;\n",
    "exercise 5 asks what would go wrong\n",
    "if the two shapes did not match.\n",
    "We return the averaged loss value\n",
    "among all examples in the minibatch."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "linear-regression-scratch-defining-the-loss-function"
   },
   "source": [
    "@d2l.add_to_class(LinearRegressionScratch)\n",
    "def loss(self, y_hat, y):\n",
    "    l = (y_hat - y) ** 2 / 2\n",
    "    return d2l.reduce_mean(l)"
   ],
   "execution_count": 4,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=linear-regression-scratch-md-5 fw=all -->\n",
    "\n",
    "Before handing this loss to an optimizer, compute by hand the\n",
    "gradient that the optimizer will consume. For a single example, the loss is\n",
    "$\\ell = \\frac{1}{2}(\\hat{y} - y)^2$ with $\\hat{y} = \\mathbf{w}^\\top \\mathbf{x} + b$,\n",
    "and the chain rule gives\n",
    "\n",
    "$$\\frac{\\partial \\ell}{\\partial \\mathbf{w}} = (\\hat{y} - y)\\, \\mathbf{x} \\qquad \\textrm{and} \\qquad \\frac{\\partial \\ell}{\\partial b} = \\hat{y} - y.$$\n",
    "\n",
    "Differentiating the square produces the error $\\hat{y} - y$, which is then\n",
    "multiplied by the derivative of $\\hat{y}$ with respect to each parameter:\n",
    "$\\mathbf{x}$ for the weights and $1$ for the bias. In words, *the gradient is\n",
    "the error-weighted input*: each weight $w_j$ will be nudged in proportion to\n",
    "how wrong the prediction was times how strongly $x_j$ contributed to it, and\n",
    "the bias simply soaks up the average error. Averaging these per-example\n",
    "gradients over a minibatch recovers exactly the closed-form update we wrote\n",
    "down in the equation. This averaged gradient is precisely\n",
    "what the backward pass deposits in each parameter's gradient field, so when\n",
    "the `SGD` class below reads `param.grad`, you now know what it contains.\n",
    "\n",
    "## Defining the Optimization Algorithm\n",
    "\n",
    "As discussed in that section,\n",
    "linear regression has a closed-form solution.\n",
    "However, our goal here is to illustrate \n",
    "how to train more general neural networks,\n",
    "and that requires that we teach you \n",
    "how to use minibatch SGD.\n",
    "Hence we will take this opportunity\n",
    "to introduce your first working example of SGD.\n",
    "At each step, using a minibatch \n",
    "randomly drawn from our dataset,\n",
    "we estimate the gradient of the loss\n",
    "with respect to the parameters.\n",
    "Next, we update the parameters\n",
    "in the direction that may reduce the loss.\n",
    "\n",
    "The following code applies the update, \n",
    "given a set of parameters, and a learning rate `lr`.\n",
    "Since our loss is computed as an average over the minibatch, \n",
    "we do not need to adjust the learning rate against the batch size. \n",
    "In later chapters we will investigate \n",
    "how learning rates should be adjusted\n",
    "for very large minibatches as they arise \n",
    "in distributed large-scale learning.\n",
    "For now, we can ignore this dependency."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=linear-regression-scratch-md-6 fw=mxnet -->\n",
    "\n",
    "We define our `SGD` class, \n",
    "a subclass of `d2l.HyperParameters` (introduced in that section),\n",
    "to have a similar API\n",
    "as the built-in SGD optimizer.\n",
    "We update the parameters in the `step` method.\n",
    "It accepts a `batch_size` argument that can be ignored."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "linear-regression-scratch-defining-the-optimization-algorithm-1"
   },
   "source": [
    "class SGD(d2l.HyperParameters):\n",
    "    \"\"\"Minibatch stochastic gradient descent.\"\"\"\n",
    "    def __init__(self, params, lr):\n",
    "        self.save_hyperparameters()\n",
    "\n",
    "    def step(self, _):\n",
    "        for param in self.params:\n",
    "            param -= self.lr * param.grad"
   ],
   "execution_count": 5,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=linear-regression-scratch-md-7 fw=all -->\n",
    "\n",
    "Every optimization step is built from the same moves: a forward pass and loss, a\n",
    "backward pass that fills each parameter's gradient with $\\partial L/\\partial\n",
    "\\theta$ averaged over the minibatch, and an update that subtracts $\\eta$ times the\n",
    "gradient from each parameter, *in place*. Two invariants govern their order. First,\n",
    "if the backward pass *accumulates* into whatever gradient is already stored\n",
    "(that section), those buffers must be cleared before it runs, or a\n",
    "leftover gradient from the previous minibatch contaminates this one. Second, the\n",
    "update must run last and *outside* the gradient graph, so that the subtraction is\n",
    "not itself differentiated and does not extend the graph; this is why it sits under\n",
    "a no-tracking guard. Miss the clearing and stale gradients leak from one batch into\n",
    "the next; miss the guard and the update either errors or silently grows the graph.\n",
    "Strip away the bookkeeping and training a neural network is exactly this loop, run\n",
    "on minibatch after minibatch, which is what `fit_epoch` implements below.\n",
    "\n",
    "We next define the `configure_optimizers` method, which returns an instance of the `SGD` class."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "linear-regression-scratch-defining-the-optimization-algorithm-2"
   },
   "source": [
    "@d2l.add_to_class(LinearRegressionScratch)\n",
    "def configure_optimizers(self):\n",
    "    return SGD([self.w, self.b], self.lr)"
   ],
   "execution_count": 6,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=linear-regression-scratch-md-8 fw=all -->\n",
    "\n",
    "## Training\n",
    "\n",
    "Now that we have all of the parts in place\n",
    "(parameters, loss function, model, and optimizer),\n",
    "we are ready to implement the main training loop.\n",
    "You will want to understand this code fully,\n",
    "since you will employ similar training loops\n",
    "for every other deep learning model\n",
    "covered in this book.\n",
    "In each *epoch*, we iterate through \n",
    "the entire training dataset, \n",
    "passing once through every example\n",
    "(up to a final partial batch when the number of examples \n",
    "is not divisible by the batch size). \n",
    "In each *iteration*, we grab a minibatch of training examples,\n",
    "and compute its loss through the model's `training_step` method. \n",
    "Then we compute the gradients with respect to each parameter. \n",
    "Finally, we will call the optimization algorithm\n",
    "to update the model parameters. \n",
    "In summary, we will execute the following loop:\n",
    "\n",
    "* Initialize parameters $(\\mathbf{w}, b)$\n",
    "* Repeat until done\n",
    "    * Compute gradient $\\mathbf{g} \\leftarrow \\partial_{(\\mathbf{w},b)} \\frac{1}{|\\mathcal{B}|} \\sum_{i \\in \\mathcal{B}} l(\\mathbf{x}^{(i)}, y^{(i)}, \\mathbf{w}, b)$\n",
    "    * Update parameters $(\\mathbf{w}, b) \\leftarrow (\\mathbf{w}, b) - \\eta \\mathbf{g}$\n",
    " \n",
    "Recall that the synthetic regression data module \n",
    "that we generated in that section \n",
    "holds out 1000 validation examples \n",
    "alongside the training data. \n",
    "We will almost always want such a validation dataset \n",
    "to measure our model quality. \n",
    "Here we pass the validation dataloader \n",
    "once in each epoch to measure the model performance.\n",
    "Following our object-oriented design,\n",
    "the `prepare_batch` and `fit_epoch` methods\n",
    "are registered in the `d2l.Trainer` class\n",
    "(introduced in that section)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "linear-regression-scratch-training-1"
   },
   "source": [
    "@d2l.add_to_class(d2l.Trainer)\n",
    "def prepare_batch(self, batch):\n",
    "    return batch"
   ],
   "execution_count": 7,
   "outputs": []
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "linear-regression-scratch-training-2"
   },
   "source": [
    "@d2l.add_to_class(d2l.Trainer)\n",
    "def fit_epoch(self):\n",
    "    for batch in self.train_dataloader:\n",
    "        with autograd.record():\n",
    "            loss = self.model.training_step(self.prepare_batch(batch))\n",
    "        loss.backward()\n",
    "        if self.gradient_clip_val > 0:\n",
    "            self.clip_gradients(self.gradient_clip_val, self.model)\n",
    "        self.optim.step(1)\n",
    "        self.train_batch_idx += 1\n",
    "    if self.val_dataloader is None:\n",
    "        return\n",
    "    for batch in self.val_dataloader:        \n",
    "        self.model.validation_step(self.prepare_batch(batch))\n",
    "        self.val_batch_idx += 1"
   ],
   "execution_count": 8,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=linear-regression-scratch-md-9 fw=all -->\n",
    "\n",
    "We are almost ready to train the model,\n",
    "but first we need some training data.\n",
    "Here we use the `SyntheticRegressionData` class \n",
    "and pass in some ground truth parameters.\n",
    "Then we train our model with \n",
    "the learning rate `lr=0.03`\n",
    "and set `max_epochs=10`.\n",
    "Note that in general, both the number of epochs \n",
    "and the learning rate are hyperparameters.\n",
    "Setting hyperparameters is tricky\n",
    "and we will usually want to use a three-way split,\n",
    "one set for training, \n",
    "a second for hyperparameter selection,\n",
    "and the third reserved for the final evaluation.\n",
    "We elide these details for now and develop model selection, validation, and the\n",
    "train/validation/test split in that section.\n",
    "\n",
    "So that repeated runs of this notebook produce identical numbers, we first fix\n",
    "the seed of the framework's random number generator, which governs both the\n",
    "parameter initialization and the shuffling of minibatches."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "linear-regression-scratch-training-seed"
   },
   "source": [
    "npx.random.seed(1)"
   ],
   "execution_count": 9,
   "outputs": []
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "linear-regression-scratch-training-3"
   },
   "source": [
    "model = LinearRegressionScratch(2, lr=0.03)\n",
    "data = d2l.SyntheticRegressionData(w=d2l.tensor([2, -3.4]), b=4.2)\n",
    "trainer = d2l.Trainer(max_epochs=10)\n",
    "trainer.fit(model, data)"
   ],
   "execution_count": 10,
   "outputs": [
    {
     "output_type": "display_data",
     "data": {
      "image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"245.328125pt\" height=\"183.35625pt\" viewBox=\"0 0 245.328125 183.35625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n <metadata>\n  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n   <cc:Work>\n    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n    <dc:date>2026-07-19T15:30:52.422387</dc:date>\n    <dc:format>image/svg+xml</dc:format>\n    <dc:creator>\n     <cc:Agent>\n      <dc:title>Matplotlib v3.10.8, https://matplotlib.org/</dc:title>\n     </cc:Agent>\n    </dc:creator>\n   </cc:Work>\n  </rdf:RDF>\n </metadata>\n <defs>\n  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n </defs>\n <g id=\"figure_1\">\n  <g id=\"patch_1\">\n   <path d=\"M 0 183.35625 \nL 245.328125 183.35625 \nL 245.328125 0 \nL 0 0 \nz\n\" style=\"fill: #ffffff\"/>\n  </g>\n  <g id=\"axes_1\">\n   <g id=\"patch_2\">\n    <path d=\"M 36.465625 145.8 \nL 231.765625 145.8 \nL 231.765625 7.2 \nL 36.465625 7.2 \nz\n\" style=\"fill: #ffffff\"/>\n   </g>\n   <g id=\"matplotlib.axis_1\">\n    <g id=\"xtick_1\">\n     <g id=\"line2d_1\">\n      <defs>\n       <path id=\"m308b08d1c2\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m308b08d1c2\" x=\"36.465625\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_1\">\n      <!-- 0 -->\n      <g transform=\"translate(33.284375 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \nQ 1547 4250 1301 3770 \nQ 1056 3291 1056 2328 \nQ 1056 1369 1301 889 \nQ 1547 409 2034 409 \nQ 2525 409 2770 889 \nQ 3016 1369 3016 2328 \nQ 3016 3291 2770 3770 \nQ 2525 4250 2034 4250 \nz\nM 2034 4750 \nQ 2819 4750 3233 4129 \nQ 3647 3509 3647 2328 \nQ 3647 1150 3233 529 \nQ 2819 -91 2034 -91 \nQ 1250 -91 836 529 \nQ 422 1150 422 2328 \nQ 422 3509 836 4129 \nQ 1250 4750 2034 4750 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_2\">\n     <g id=\"line2d_2\">\n      <g>\n       <use xlink:href=\"#m308b08d1c2\" x=\"75.525625\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_2\">\n      <!-- 2 -->\n      <g transform=\"translate(72.344375 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \nL 3431 531 \nL 3431 0 \nL 469 0 \nL 469 531 \nQ 828 903 1448 1529 \nQ 2069 2156 2228 2338 \nQ 2531 2678 2651 2914 \nQ 2772 3150 2772 3378 \nQ 2772 3750 2511 3984 \nQ 2250 4219 1831 4219 \nQ 1534 4219 1204 4116 \nQ 875 4013 500 3803 \nL 500 4441 \nQ 881 4594 1212 4672 \nQ 1544 4750 1819 4750 \nQ 2544 4750 2975 4387 \nQ 3406 4025 3406 3419 \nQ 3406 3131 3298 2873 \nQ 3191 2616 2906 2266 \nQ 2828 2175 2409 1742 \nQ 1991 1309 1228 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_3\">\n     <g id=\"line2d_3\">\n      <g>\n       <use xlink:href=\"#m308b08d1c2\" x=\"114.585625\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_3\">\n      <!-- 4 -->\n      <g transform=\"translate(111.404375 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-34\" d=\"M 2419 4116 \nL 825 1625 \nL 2419 1625 \nL 2419 4116 \nz\nM 2253 4666 \nL 3047 4666 \nL 3047 1625 \nL 3713 1625 \nL 3713 1100 \nL 3047 1100 \nL 3047 0 \nL 2419 0 \nL 2419 1100 \nL 313 1100 \nL 313 1709 \nL 2253 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-34\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_4\">\n     <g id=\"line2d_4\">\n      <g>\n       <use xlink:href=\"#m308b08d1c2\" x=\"153.645625\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_4\">\n      <!-- 6 -->\n      <g transform=\"translate(150.464375 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-36\" d=\"M 2113 2584 \nQ 1688 2584 1439 2293 \nQ 1191 2003 1191 1497 \nQ 1191 994 1439 701 \nQ 1688 409 2113 409 \nQ 2538 409 2786 701 \nQ 3034 994 3034 1497 \nQ 3034 2003 2786 2293 \nQ 2538 2584 2113 2584 \nz\nM 3366 4563 \nL 3366 3988 \nQ 3128 4100 2886 4159 \nQ 2644 4219 2406 4219 \nQ 1781 4219 1451 3797 \nQ 1122 3375 1075 2522 \nQ 1259 2794 1537 2939 \nQ 1816 3084 2150 3084 \nQ 2853 3084 3261 2657 \nQ 3669 2231 3669 1497 \nQ 3669 778 3244 343 \nQ 2819 -91 2113 -91 \nQ 1303 -91 875 529 \nQ 447 1150 447 2328 \nQ 447 3434 972 4092 \nQ 1497 4750 2381 4750 \nQ 2619 4750 2861 4703 \nQ 3103 4656 3366 4563 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-36\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_5\">\n     <g id=\"line2d_5\">\n      <g>\n       <use xlink:href=\"#m308b08d1c2\" x=\"192.705625\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_5\">\n      <!-- 8 -->\n      <g transform=\"translate(189.524375 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-38\" d=\"M 2034 2216 \nQ 1584 2216 1326 1975 \nQ 1069 1734 1069 1313 \nQ 1069 891 1326 650 \nQ 1584 409 2034 409 \nQ 2484 409 2743 651 \nQ 3003 894 3003 1313 \nQ 3003 1734 2745 1975 \nQ 2488 2216 2034 2216 \nz\nM 1403 2484 \nQ 997 2584 770 2862 \nQ 544 3141 544 3541 \nQ 544 4100 942 4425 \nQ 1341 4750 2034 4750 \nQ 2731 4750 3128 4425 \nQ 3525 4100 3525 3541 \nQ 3525 3141 3298 2862 \nQ 3072 2584 2669 2484 \nQ 3125 2378 3379 2068 \nQ 3634 1759 3634 1313 \nQ 3634 634 3220 271 \nQ 2806 -91 2034 -91 \nQ 1263 -91 848 271 \nQ 434 634 434 1313 \nQ 434 1759 690 2068 \nQ 947 2378 1403 2484 \nz\nM 1172 3481 \nQ 1172 3119 1398 2916 \nQ 1625 2713 2034 2713 \nQ 2441 2713 2670 2916 \nQ 2900 3119 2900 3481 \nQ 2900 3844 2670 4047 \nQ 2441 4250 2034 4250 \nQ 1625 4250 1398 4047 \nQ 1172 3844 1172 3481 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-38\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_6\">\n     <g id=\"line2d_6\">\n      <g>\n       <use xlink:href=\"#m308b08d1c2\" x=\"231.765625\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_6\">\n      <!-- 10 -->\n      <g transform=\"translate(225.403125 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-31\" d=\"M 794 531 \nL 1825 531 \nL 1825 4091 \nL 703 3866 \nL 703 4441 \nL 1819 4666 \nL 2450 4666 \nL 2450 531 \nL 3481 531 \nL 3481 0 \nL 794 0 \nL 794 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-31\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_7\">\n     <!-- epoch -->\n     <g transform=\"translate(118.8875 174.076563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \nL 3597 1613 \nL 953 1613 \nQ 991 1019 1311 708 \nQ 1631 397 2203 397 \nQ 2534 397 2845 478 \nQ 3156 559 3463 722 \nL 3463 178 \nQ 3153 47 2828 -22 \nQ 2503 -91 2169 -91 \nQ 1331 -91 842 396 \nQ 353 884 353 1716 \nQ 353 2575 817 3079 \nQ 1281 3584 2069 3584 \nQ 2775 3584 3186 3129 \nQ 3597 2675 3597 1894 \nz\nM 3022 2063 \nQ 3016 2534 2758 2815 \nQ 2500 3097 2075 3097 \nQ 1594 3097 1305 2825 \nQ 1016 2553 972 2059 \nL 3022 2063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \nL 1159 -1331 \nL 581 -1331 \nL 581 3500 \nL 1159 3500 \nL 1159 2969 \nQ 1341 3281 1617 3432 \nQ 1894 3584 2278 3584 \nQ 2916 3584 3314 3078 \nQ 3713 2572 3713 1747 \nQ 3713 922 3314 415 \nQ 2916 -91 2278 -91 \nQ 1894 -91 1617 61 \nQ 1341 213 1159 525 \nz\nM 3116 1747 \nQ 3116 2381 2855 2742 \nQ 2594 3103 2138 3103 \nQ 1681 3103 1420 2742 \nQ 1159 2381 1159 1747 \nQ 1159 1113 1420 752 \nQ 1681 391 2138 391 \nQ 2594 391 2855 752 \nQ 3116 1113 3116 1747 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \nQ 1497 3097 1228 2736 \nQ 959 2375 959 1747 \nQ 959 1119 1226 758 \nQ 1494 397 1959 397 \nQ 2419 397 2687 759 \nQ 2956 1122 2956 1747 \nQ 2956 2369 2687 2733 \nQ 2419 3097 1959 3097 \nz\nM 1959 3584 \nQ 2709 3584 3137 3096 \nQ 3566 2609 3566 1747 \nQ 3566 888 3137 398 \nQ 2709 -91 1959 -91 \nQ 1206 -91 779 398 \nQ 353 888 353 1747 \nQ 353 2609 779 3096 \nQ 1206 3584 1959 3584 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \nL 3122 2828 \nQ 2878 2963 2633 3030 \nQ 2388 3097 2138 3097 \nQ 1578 3097 1268 2742 \nQ 959 2388 959 1747 \nQ 959 1106 1268 751 \nQ 1578 397 2138 397 \nQ 2388 397 2633 464 \nQ 2878 531 3122 666 \nL 3122 134 \nQ 2881 22 2623 -34 \nQ 2366 -91 2075 -91 \nQ 1284 -91 818 406 \nQ 353 903 353 1747 \nQ 353 2603 823 3093 \nQ 1294 3584 2113 3584 \nQ 2378 3584 2631 3529 \nQ 2884 3475 3122 3366 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 4863 \nL 1159 4863 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-65\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(61.523438 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(186.181641 0)\"/>\n      <use xlink:href=\"#DejaVuSans-68\" transform=\"translate(241.162109 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"matplotlib.axis_2\">\n    <g id=\"ytick_1\">\n     <g id=\"line2d_7\">\n      <defs>\n       <path id=\"m0b51dab5f5\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m0b51dab5f5\" x=\"36.465625\" y=\"139.500524\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- 0.0 -->\n      <g transform=\"translate(13.5625 143.299743) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \nL 1344 794 \nL 1344 0 \nL 684 0 \nL 684 794 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_8\">\n      <g>\n       <use xlink:href=\"#m0b51dab5f5\" x=\"36.465625\" y=\"111.361484\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_9\">\n      <!-- 2.5 -->\n      <g transform=\"translate(13.5625 115.160702) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \nL 3169 4666 \nL 3169 4134 \nL 1269 4134 \nL 1269 2991 \nQ 1406 3038 1543 3061 \nQ 1681 3084 1819 3084 \nQ 2600 3084 3056 2656 \nQ 3513 2228 3513 1497 \nQ 3513 744 3044 326 \nQ 2575 -91 1722 -91 \nQ 1428 -91 1123 -41 \nQ 819 9 494 109 \nL 494 744 \nQ 775 591 1075 516 \nQ 1375 441 1709 441 \nQ 2250 441 2565 725 \nQ 2881 1009 2881 1497 \nQ 2881 1984 2565 2268 \nQ 2250 2553 1709 2553 \nQ 1456 2553 1204 2497 \nQ 953 2441 691 2322 \nL 691 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_9\">\n      <g>\n       <use xlink:href=\"#m0b51dab5f5\" x=\"36.465625\" y=\"83.222443\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_10\">\n      <!-- 5.0 -->\n      <g transform=\"translate(13.5625 87.021662) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-35\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_4\">\n     <g id=\"line2d_10\">\n      <g>\n       <use xlink:href=\"#m0b51dab5f5\" x=\"36.465625\" y=\"55.083402\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_11\">\n      <!-- 7.5 -->\n      <g transform=\"translate(13.5625 58.882621) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-37\" d=\"M 525 4666 \nL 3525 4666 \nL 3525 4397 \nL 1831 0 \nL 1172 0 \nL 2766 4134 \nL 525 4134 \nL 525 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-37\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_5\">\n     <g id=\"line2d_11\">\n      <g>\n       <use xlink:href=\"#m0b51dab5f5\" x=\"36.465625\" y=\"26.944362\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_12\">\n      <!-- 10.0 -->\n      <g transform=\"translate(7.2 30.74358) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-31\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(159.033203 0)\"/>\n      </g>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_12\">\n    <path d=\"M 41.042969 13.5 \nL 50.807969 97.281559 \nL 60.572969 121.330547 \nL 70.337969 132.347664 \nL 80.102969 136.780146 \nL 89.867969 138.436829 \nL 99.632969 139.109239 \nL 109.397969 139.32951 \nL 119.162969 139.441934 \nL 128.927969 139.473267 \nL 138.692969 139.490768 \nL 148.457969 139.49638 \nL 158.222969 139.498582 \nL 167.987969 139.499451 \nL 177.752969 139.499703 \nL 187.517969 139.499927 \nL 197.282969 139.499914 \nL 207.047969 139.5 \nL 216.812969 139.499975 \nL 226.577969 139.49997 \n\" clip-path=\"url(#p8e6bfcec74)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"line2d_13\">\n    <path d=\"M 55.995625 110.16764 \nL 75.525625 135.139566 \nL 95.055625 138.853732 \nL 114.585625 139.402969 \nL 134.115625 139.485409 \nL 153.645625 139.497808 \nL 173.175625 139.499626 \nL 192.705625 139.499902 \nL 212.235625 139.499945 \nL 231.765625 139.499948 \n\" clip-path=\"url(#p8e6bfcec74)\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #ff7f0e; stroke-width: 1.5\"/>\n   </g>\n   <g id=\"patch_3\">\n    <path d=\"M 36.465625 145.8 \nL 36.465625 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_4\">\n    <path d=\"M 231.765625 145.8 \nL 231.765625 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_5\">\n    <path d=\"M 36.465625 145.8 \nL 231.765625 145.8 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_6\">\n    <path d=\"M 36.465625 7.2 \nL 231.765625 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"legend_1\">\n    <g id=\"patch_7\">\n     <path d=\"M 145.175 45.1125 \nL 224.765625 45.1125 \nQ 226.765625 45.1125 226.765625 43.1125 \nL 226.765625 14.2 \nQ 226.765625 12.2 224.765625 12.2 \nL 145.175 12.2 \nQ 143.175 12.2 143.175 14.2 \nL 143.175 43.1125 \nQ 143.175 45.1125 145.175 45.1125 \nz\n\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n    </g>\n    <g id=\"line2d_14\">\n     <path d=\"M 147.175 20.298438 \nL 157.175 20.298438 \nL 167.175 20.298438 \n\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n    </g>\n    <g id=\"text_13\">\n     <!-- train_loss -->\n     <g transform=\"translate(175.175 23.798438) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-74\" d=\"M 1172 4494 \nL 1172 3500 \nL 2356 3500 \nL 2356 3053 \nL 1172 3053 \nL 1172 1153 \nQ 1172 725 1289 603 \nQ 1406 481 1766 481 \nL 2356 481 \nL 2356 0 \nL 1766 0 \nQ 1100 0 847 248 \nQ 594 497 594 1153 \nL 594 3053 \nL 172 3053 \nL 172 3500 \nL 594 3500 \nL 594 4494 \nL 1172 4494 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-72\" d=\"M 2631 2963 \nQ 2534 3019 2420 3045 \nQ 2306 3072 2169 3072 \nQ 1681 3072 1420 2755 \nQ 1159 2438 1159 1844 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1341 3275 1631 3429 \nQ 1922 3584 2338 3584 \nQ 2397 3584 2469 3576 \nQ 2541 3569 2628 3553 \nL 2631 2963 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-61\" d=\"M 2194 1759 \nQ 1497 1759 1228 1600 \nQ 959 1441 959 1056 \nQ 959 750 1161 570 \nQ 1363 391 1709 391 \nQ 2188 391 2477 730 \nQ 2766 1069 2766 1631 \nL 2766 1759 \nL 2194 1759 \nz\nM 3341 1997 \nL 3341 0 \nL 2766 0 \nL 2766 531 \nQ 2569 213 2275 61 \nQ 1981 -91 1556 -91 \nQ 1019 -91 701 211 \nQ 384 513 384 1019 \nQ 384 1609 779 1909 \nQ 1175 2209 1959 2209 \nL 2766 2209 \nL 2766 2266 \nQ 2766 2663 2505 2880 \nQ 2244 3097 1772 3097 \nQ 1472 3097 1187 3025 \nQ 903 2953 641 2809 \nL 641 3341 \nQ 956 3463 1253 3523 \nQ 1550 3584 1831 3584 \nQ 2591 3584 2966 3190 \nQ 3341 2797 3341 1997 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-69\" d=\"M 603 3500 \nL 1178 3500 \nL 1178 0 \nL 603 0 \nL 603 3500 \nz\nM 603 4863 \nL 1178 4863 \nL 1178 4134 \nL 603 4134 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6e\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-5f\" d=\"M 3263 -1063 \nL 3263 -1509 \nL -63 -1509 \nL -63 -1063 \nL 3263 -1063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \nL 1178 4863 \nL 1178 0 \nL 603 0 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \nL 2834 2853 \nQ 2591 2978 2328 3040 \nQ 2066 3103 1784 3103 \nQ 1356 3103 1142 2972 \nQ 928 2841 928 2578 \nQ 928 2378 1081 2264 \nQ 1234 2150 1697 2047 \nL 1894 2003 \nQ 2506 1872 2764 1633 \nQ 3022 1394 3022 966 \nQ 3022 478 2636 193 \nQ 2250 -91 1575 -91 \nQ 1294 -91 989 -36 \nQ 684 19 347 128 \nL 347 722 \nQ 666 556 975 473 \nQ 1284 391 1588 391 \nQ 1994 391 2212 530 \nQ 2431 669 2431 922 \nQ 2431 1156 2273 1281 \nQ 2116 1406 1581 1522 \nL 1381 1569 \nQ 847 1681 609 1914 \nQ 372 2147 372 2553 \nQ 372 3047 722 3315 \nQ 1072 3584 1716 3584 \nQ 2034 3584 2315 3537 \nQ 2597 3491 2834 3397 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-74\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(39.208984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(80.322266 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(141.601562 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(169.384766 0)\"/>\n      <use xlink:href=\"#DejaVuSans-5f\" transform=\"translate(232.763672 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(282.763672 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(310.546875 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(371.728516 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(423.828125 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_15\">\n     <path d=\"M 147.175 35.254688 \nL 157.175 35.254688 \nL 167.175 35.254688 \n\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #ff7f0e; stroke-width: 1.5\"/>\n    </g>\n    <g id=\"text_14\">\n     <!-- val_loss -->\n     <g transform=\"translate(175.175 38.754688) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-76\" d=\"M 191 3500 \nL 800 3500 \nL 1894 563 \nL 2988 3500 \nL 3597 3500 \nL 2284 0 \nL 1503 0 \nL 191 3500 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-76\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(59.179688 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(120.458984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-5f\" transform=\"translate(148.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(198.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(226.025391 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(287.207031 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(339.306641 0)\"/>\n     </g>\n    </g>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"p8e6bfcec74\">\n   <rect x=\"36.465625\" y=\"7.2\" width=\"195.3\" height=\"138.6\"/>\n  </clipPath>\n </defs>\n</svg>\n"
     },
     "metadata": {}
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=linear-regression-scratch-md-10 fw=all -->\n",
    "\n",
    "The `fit` call above produces a live plot of the training and validation loss\n",
    "against the epoch. Both curves fall together and flatten near the irreducible\n",
    "noise floor (with $\\sigma = 0.01$ the per-example squared loss bottoms out around\n",
    "$\\sigma^2/2 \\approx 5\\times 10^{-5}$). The validation curve tracks the\n",
    "training curve with **no gap**: a two-dimensional linear model fit on 1000\n",
    "examples has no capacity to overfit. We return to the train/validation gap, and\n",
    "what to do when it opens, in that section.\n",
    "\n",
    "Because we synthesized the dataset ourselves,\n",
    "we know precisely what the true parameters are.\n",
    "Thus, we can evaluate our success in training\n",
    "by comparing the true parameters\n",
    "with those that we learned through our training loop.\n",
    "Indeed they turn out to be very close to each other."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "linear-regression-scratch-training-4"
   },
   "source": [
    "print(f'error in estimating w: {data.w - d2l.reshape(model.w, data.w.shape)}')\n",
    "print(f'error in estimating b: {data.b - model.b}')"
   ],
   "execution_count": 11,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "error in estimating w: [ 0.00030959 -0.00010204]\nerror in estimating b: [8.4877014e-05]\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=linear-regression-scratch-md-11 fw=all -->\n",
    "\n",
    "We should not take the ability to exactly recover \n",
    "the ground truth parameters for granted.\n",
    "In general, for deep models unique solutions\n",
    "for the parameters do not exist,\n",
    "and even for linear models,\n",
    "exactly recovering the parameters\n",
    "is only possible when no feature \n",
    "is linearly dependent on the others.\n",
    "However, in machine learning, \n",
    "we are often less concerned\n",
    "with recovering true underlying parameters,\n",
    "but rather with parameters \n",
    "that lead to highly accurate prediction [@Vapnik.1992].\n",
    "Fortunately, even on difficult optimization problems,\n",
    "stochastic gradient descent can often find good solutions,\n",
    "owing partly to the fact that, for deep networks,\n",
    "there exist many configurations of the parameters\n",
    "that lead to highly accurate prediction.\n",
    "Why the solutions that SGD finds among these many candidates\n",
    "also *generalize* so well is a deep question,\n",
    "taken up in that section.\n",
    "\n",
    "\n",
    "## Summary\n",
    "\n",
    "In this section, we took a significant step \n",
    "towards designing deep learning systems \n",
    "by implementing a fully functional \n",
    "neural network model and training loop.\n",
    "In this process, we built a data loader, \n",
    "a model, a loss function, an optimization procedure,\n",
    "and a visualization and monitoring tool. \n",
    "We did this by composing a Python object \n",
    "that contains all relevant components for training a model. \n",
    "While this is not yet a professional-grade implementation\n",
    "it is perfectly functional and code like this \n",
    "could already help you to solve small problems quickly.\n",
    "In the coming sections, we will see how to do this\n",
    "both *more concisely* (avoiding boilerplate code)\n",
    "and *more efficiently* (using our GPUs to their full potential).\n",
    "\n",
    "The hand-rolled SGD above is the simplest member of a large family: momentum,\n",
    "AdaGrad, RMSProp, and Adam all replace that single update line, and learning-rate\n",
    "schedules anneal $\\eta$ over the course of training; these are developed in\n",
    "that section. The squared loss, likewise, is a modelling\n",
    "choice; in that section we add a penalty on $\\|\\mathbf{w}\\|$ to\n",
    "curb overfitting, the first of many regularizers we will meet.\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. What would happen if we were to initialize the weights to zero. Would the algorithm still work? What if we\n",
    "   initialized the parameters with variance $1000$ rather than $0.01$?\n",
    "1. Assume that you are [Georg Simon Ohm](https://en.wikipedia.org/wiki/Georg_Ohm) trying to come up\n",
    "   with a model for resistance that relates voltage and current. Can you use automatic\n",
    "   differentiation to learn the parameters of your model?\n",
    "1. Can you use [Planck's Law](https://en.wikipedia.org/wiki/Planck%27s_law) to determine the temperature of an object\n",
    "   using spectral energy density? For reference, the spectral density $B$ of radiation emanating from a black body is\n",
    "   $B(\\lambda, T) = \\frac{2 hc^2}{\\lambda^5} \\cdot \\left(\\exp \\frac{h c}{\\lambda k T} - 1\\right)^{-1}$. Here\n",
    "   $\\lambda$ is the wavelength, $T$ is the temperature, $c$ is the speed of light, $h$ is Planck's constant, and $k$ is the\n",
    "   Boltzmann constant. You measure the energy for different wavelengths $\\lambda$ and you now need to fit the spectral\n",
    "   density curve to Planck's law.\n",
    "1. What are the problems you might encounter if you wanted to compute the second derivatives of the loss? How would\n",
    "   you fix them?\n",
    "1. Why is the `reshape` method needed in the `loss` function?\n",
    "1. Experiment using different learning rates to find out how quickly the loss function value drops. Can you reduce the\n",
    "   error by increasing the number of epochs of training?\n",
    "1. Try implementing a different loss function, such as the absolute value loss `(y_hat - d2l.reshape(y, y_hat.shape)).abs().mean()`. (If you *sum* rather than average, the gradient scales with the batch size, so you must lower the learning rate to compensate.)\n",
    "    1. Check what happens for regular data.\n",
    "    1. Check whether there is a difference in behavior if you actively perturb some entries, such as $y_5 = 10000$, of $\\mathbf{y}$.\n",
    "    1. Can you think of a cheap solution for combining the best aspects of squared loss and absolute value loss?\n",
    "       Hint: how can you avoid really large gradient values?\n",
    "1. Why do we need to reshuffle the dataset? Can you design a case where a maliciously constructed dataset would break the optimization algorithm otherwise?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=linear-regression-scratch-md-12 fw=mxnet -->\n",
    "\n",
    "[Discussions](https://d2l.discourse.group/t/42)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "d2l-mxnet",
   "display_name": "d2l (MXNet)",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
