{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8dbd27bb",
   "metadata": {},
   "source": [
    "# Solutions to exercises from [chapter 1 of Neural networks and deep learning](http://neuralnetworksanddeeplearning.com/chap1.html)\n",
    "\n",
    "By [Peter Bessman](https://peter.bessman.co)\n",
    "\n",
    "Thanks to [Michael Nielsen](https://michaelnielsen.org/) for generously making this great book available for free."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a56133fe",
   "metadata": {},
   "source": [
    "## Ex1: Sigmoid neurons simulating perceptrons, part I"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6a01d58d",
   "metadata": {},
   "source": [
    "> **Exercise:** Suppose we take all the weights and biases in a network of perceptrons, and multiply them by a positive constant, $c>0$ . Show that the behaviour of the network doesn't change."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e07d752c",
   "metadata": {},
   "source": [
    "The key insight is that if this modification doesn't change the output of an individual perceptron, then it won't change the output of the network. More specifically, if scaling all weights and biases by a constant doesn't change the output of a perceptron, then all perceptrons in the input layer will produce the same output, and all perceptrons in the next layer will receive the same input — and scaling this input won't change their output, so the perceptrons in the *next* layer will receive the same input, produce the same output... and so on until we arrive at the output layer producing the same final outputs as before we introduced the scaling term.\n",
    "\n",
    "If we write a function to calculate the weighted input for a perceptron, everything becomes intuitively obvious:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "26727aa8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Take in weights and biases (w1, w2, b), input values (x1, x2) and a scaling term (c).\n",
    "# Return the weighted input for a perceptron, with weights and biases scaled by c.\n",
    "def z(w1, w2, b, x1, x2, c = 1):\n",
    "    return (w1*c)*x1 + (w2*c)*x2 + (b*c)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db2919d1",
   "metadata": {},
   "source": [
    "We easily see that the scaling term $c$ can't change the sign of the result if $c > 0$, because:\n",
    "\n",
    "$$ (w_1 c) x_1  + (w_2 c) x_2 + (b c) = c(w_1 x_1 + w_2 x_2 + b) $$\n",
    "\n",
    "Which is readily observed by running the function on a few exemplary scenarios:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e2088b45",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "unscaled: 2, scaled: 4\n"
     ]
    }
   ],
   "source": [
    "scaling_term = 2\n",
    "unscaled = z(6, 3, -4, 1, 0)\n",
    "scaled = z(6, 3, -4, 1, 0, scaling_term)\n",
    "\n",
    "print(f\"unscaled: {unscaled}, scaled: {scaled}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "70e14f18",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "unscaled: -1, scaled: -2\n"
     ]
    }
   ],
   "source": [
    "unscaled = z(6, 3, -4, 0, 1)\n",
    "scaled = z(6, 3, -4, 0, 1, scaling_term)\n",
    "\n",
    "print(f\"unscaled: {unscaled}, scaled: {scaled}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b62e15eb",
   "metadata": {},
   "source": [
    "Because the sign of the result of the weighted input function doesn't change, the output of the perceptron won't change given the standard activation function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "fe391e50",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "unscaled output: 1, scaled output: 1\n",
      "unscaled output: 0, scaled output: 0\n"
     ]
    }
   ],
   "source": [
    "# Return the output of a perceptron for a given weighted input.\n",
    "def activate(weighted_input):\n",
    "    if weighted_input <= 0:\n",
    "        return 0\n",
    "    else:\n",
    "        return 1\n",
    "    \n",
    "unscaled = z(6, 3, -4, 1, 0)\n",
    "unscaled_output = activate(unscaled)\n",
    "scaled = z(6, 3, -4, 1, 0, scaling_term)\n",
    "scaled_output = activate(scaled)\n",
    "print(f\"unscaled output: {unscaled_output}, scaled output: {scaled_output}\")\n",
    "\n",
    "unscaled = z(6, 3, -4, 0, 1)\n",
    "unscaled_output = activate(unscaled)\n",
    "scaled = z(6, 3, -4, 0, 1, scaling_term)\n",
    "scaled_output = activate(scaled)\n",
    "print(f\"unscaled output: {unscaled_output}, scaled output: {scaled_output}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8c07390",
   "metadata": {},
   "source": [
    "## Ex2: Sigmoid neurons simulating perceptrons, part II"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8218e0d",
   "metadata": {},
   "source": [
    "> **Exercise:** Suppose we have the same setup as the last problem - a network of perceptrons. Suppose also that the overall input to the network of perceptrons has been chosen. We won't need the actual input value, we just need the input to have been fixed. Suppose the weights and biases are such that ${w \\cdot x + b \\neq 0}$ for the input x to any particular perceptron in the network. Now replace all the perceptrons in the network by sigmoid neurons, and multiply the weights and biases by a positive constant ${c>0}$ . Show that in the limit as ${c \\rightarrow \\infty}$ the behaviour of this network of sigmoid neurons is exactly the same as the network of perceptrons. How can this fail when ${w \\cdot x + b = 0}$ for one of the perceptrons?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e64a203d",
   "metadata": {},
   "source": [
    "Consider the input to the sigmoid function:\n",
    "\n",
    "$$\\sigma(w \\cdot x + b)$$\n",
    "\n",
    "This outputs on the interval $(0, 1)$ no matter what. The more positive the input, the closer the output is to $1$; the more negative the input, the closer the output is to $0$.\n",
    "\n",
    "$$0 < \\sigma(w \\cdot x + b) < 1$$\n",
    "\n",
    "Now start scaling $w$ and $b$ by infinity:\n",
    "\n",
    "$$\\sigma(\\infty \\cdot w \\cdot x + \\infty \\cdot b)$$\n",
    "\n",
    "$$\\sigma(\\infty \\cdot (w \\cdot x + b))$$\n",
    "\n",
    "Given the constraint that $w \\cdot x + b \\neq 0$ for any given $x$, we will have:\n",
    "\n",
    "$$\\sigma(\\pm\\infty)$$\n",
    "\n",
    "Recall the definition of the sigmoid function:\n",
    "\n",
    "$$ \\sigma(z) \\equiv \\frac{1}{1+e^{-z}} $$\n",
    "\n",
    "In the limit as $z$ approaches positive or negative infinity, this will output $0$ or $1$, just like a perceptron.\n",
    "\n",
    "$$ \\lim_{z \\to \\pm\\infty} \\frac{1}{1+e^{-z}} \\longrightarrow \\frac{1}{1+\\{\\infty, 0\\}} = \\{0, 1\\} $$\n",
    "\n",
    "Without the constraint, we could have some situations where $w \\cdot x + b = 0$,  leading to $\\sigma(0) = 0.5$.\n",
    "\n",
    "$$  \\frac{1}{1+e^{-0}} \\longrightarrow \\frac{1}{1+1} = 0.5 $$\n",
    "\n",
    "Since a perceptron ought to output one of $ \\{ 0, 1 \\} $ we cannot claim that a sigmoid neuron is functionally equivalent if it outputs $\\{ 0, 0.5, 1 \\} $."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "584a1c56",
   "metadata": {},
   "source": [
    "## Ex3: Determining the bitwise representation of a digit"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "977ba9e3",
   "metadata": {},
   "source": [
    "> **Exercise:** There is a way of determining the bitwise representation of a digit by adding an extra layer to the three-layer network above. The extra layer converts the output from the previous layer into a binary representation, as illustrated in the figure below. Find a set of weights and biases for the new output layer. Assume that the first 3 layers of neurons are such that the correct output in the third layer (i.e., the old output layer) has activation at least 0.99 , and incorrect outputs have activation less than 0.01 ."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "291b6267",
   "metadata": {},
   "source": [
    "This is straightforwardly illustrated in code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f64a3c2e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def dot_product(a, b):\n",
    "    result = 0\n",
    "    for i in range(len(a)):\n",
    "        result += a[i] * b[i]\n",
    "    \n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0a204baa",
   "metadata": {},
   "outputs": [],
   "source": [
    "def unbiased_sigmoid_neuron(weights, inputs):\n",
    "    dp = dot_product(inputs, weights) # Pre-activation.\n",
    "    result = 1.0 / (1.0 + m.exp(-dp)) # Activation.\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "2c44f243",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "digit 0: 0000\n",
      "digit 1: 0001\n",
      "digit 2: 0010\n",
      "digit 3: 0011\n",
      "digit 4: 0100\n",
      "digit 5: 0101\n",
      "digit 6: 0110\n",
      "digit 7: 0111\n",
      "digit 8: 1000\n",
      "digit 9: 1001\n"
     ]
    }
   ],
   "source": [
    "import math as m\n",
    "\n",
    "# Takes an output layer of digits and adds another layer to determine binary bits corresponding to that digit.\n",
    "def digit_bits():\n",
    "    Y = 0.99\n",
    "    N = 0.01\n",
    "    digits = [\n",
    "        #0  1  2  3  4  5  6  7  8  9\n",
    "        [Y, N, N, N, N, N, N, N, N, N], #0\n",
    "        [N, Y, N, N, N, N, N, N, N, N], #1\n",
    "        [N, N, Y, N, N, N, N, N, N, N], #2\n",
    "        [N, N, N, Y, N, N, N, N, N, N], #3\n",
    "        [N, N, N, N, Y, N, N, N, N, N], #4\n",
    "        [N, N, N, N, N, Y, N, N, N, N], #5\n",
    "        [N, N, N, N, N, N, Y, N, N, N], #6\n",
    "        [N, N, N, N, N, N, N, Y, N, N], #7\n",
    "        [N, N, N, N, N, N, N, N, Y, N], #8\n",
    "        [N, N, N, N, N, N, N, N, N, Y], #9\n",
    "    ]\n",
    "\n",
    "    W = 1\n",
    "    weights = [\n",
    "        # 0   1   2   3   4   5   6   7   8   9\n",
    "        [-W,  W, -W,  W, -W,  W, -W,  W, -W,  W], #0001\n",
    "        [-W, -W,  W,  W, -W, -W,  W,  W, -W, -W], #0010\n",
    "        [-W, -W, -W, -W,  W,  W,  W,  W, -W, -W], #0100\n",
    "        [-W, -W, -W, -W, -W, -W, -W, -W,  W,  W], #1000\n",
    "    ]\n",
    "\n",
    "    # No bias necessary, this alone is enough to do the job, we just take anything above 0.5 as indicating \"this bit is active for this digit.\"\n",
    "    for i in range(10):\n",
    "        binary = \"\"\n",
    "        for j in range(4):\n",
    "            result = unbiased_sigmoid_neuron(digits[i], weights[j])\n",
    "            binary = str(int(result+0.5)) + binary\n",
    "        print(f\"digit {i}: {binary}\")\n",
    "\n",
    "digit_bits()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68a81c65",
   "metadata": {},
   "source": [
    "## Ex4: Proving that the gradient is the direction of steepest ascent"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "564c4640",
   "metadata": {},
   "source": [
    "> It can be proved that the choice of ${\\Delta v}$ which minimizes ${\\nabla C \\cdot \\Delta v}$ is ${\\Delta v = - \\eta \\nabla C}$, where ${\\eta = \\epsilon / \\|\\nabla C\\|}$ is determined by the size constraint ${\\|\\Delta v\\| = \\epsilon}$. So gradient descent can be viewed as a way of taking small steps in the direction which does the most to immediately decrease $C$.\n",
    "\n",
    "> **Exercise:** Prove the assertion of the last paragraph. Hint: If you're not already familiar with the [Cauchy-Schwarz inequality](http://en.wikipedia.org/wiki/Cauchy%E2%80%93Schwarz_inequality), you may find it helpful to familiarize yourself with it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ca44d90",
   "metadata": {},
   "source": [
    "By the [Cauchy-Schwarz inequality](https://artofproblemsolving.com/wiki/index.php/Cauchy-Schwarz_Inequality), we know that:\n",
    "\n",
    "$$ | \\vec{u} \\cdot \\vec{v} | \\leq \\| \\vec{u} \\| \\|\\vec{v} \\|$$\n",
    "\n",
    "For non-zero vectors, it also holds that equality is attained if and only if there is some $ t $ such that ${ \\vec{v} = t \\vec{u} }$, meaning:\n",
    "\n",
    "$$ | \\vec{u} \\cdot t\\vec{u} | = \\| \\vec{u} \\| \\| t\\vec{u} \\|$$\n",
    "\n",
    "Which can be restated as:\n",
    "\n",
    "$$\n",
    "\\vec{u} \\cdot t\\vec{u} = \\begin{cases} \n",
    "\\| \\vec{u} \\| \\| t \\vec{u}\\| (-1) & \\longrightarrow t < 0 \\\\ \n",
    "\\| \\vec{u} \\| \\| t \\vec{u}\\| & \\longrightarrow t \\geq 0 \n",
    "\\end{cases}\n",
    "$$\n",
    "\n",
    "These represent the **lower** and **upper** bounds of ${ \\vec{u} \\cdot \\vec{v} }$, respectively.\n",
    "\n",
    "We're trying to minimize ${ \\Delta C \\approx \\nabla C \\cdot \\Delta v }$, which tends to hold when $ \\Delta v $ is very small. From the above it follows that:\n",
    "\n",
    "$$ |\\nabla C \\cdot \\Delta v | \\leq \\| \\nabla C \\| \\| \\Delta v \\| $$\n",
    "\n",
    "Given a small ${ \\eta > 0 }$ we can state our lower bound as:\n",
    "\n",
    "$$ \\| \\nabla C \\| \\| -\\eta \\nabla C \\| (-1) = \\nabla C \\cdot (-\\eta) \\nabla C $$\n",
    "\n",
    "So for any given $ \\nabla C $, **we expect to minimize** $ \\Delta C $ when ${ \\Delta v = - \\eta \\nabla C }$.\n",
    "\n",
    "To determine an appropriate $ \\eta $, we first constrain the magnitude of $ \\Delta v $ such that ${ \\| \\Delta v \\| = \\epsilon }$ for some small fixed ${ \\epsilon > 0 }$. Then because ${ \\| \\Delta v \\| = \\| - \\eta \\nabla C \\| }$, we can see that:\n",
    "\n",
    "$$\n",
    "\\begin{align*}\n",
    "\\| - \\eta \\nabla C \\| &= \\epsilon \\\\\n",
    "\\eta \\| \\nabla C \\| &= \\epsilon \\\\\n",
    "\\eta  &= \\frac{\\epsilon}{\\| \\nabla C \\|}\n",
    "\\end{align*}\n",
    "$$\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7afc0e51",
   "metadata": {},
   "source": [
    "## Ex5: Gradient descent of one variable"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8efc8f30",
   "metadata": {},
   "source": [
    "> **Exercise:** I explained gradient descent when C is a function of two variables, and when it's a function of more than two variables. What happens when C is a function of just one variable? Can you provide a geometric interpretation of what gradient descent is doing in the one-dimensional case?\n",
    "\n",
    "When $ C $ is a function of one variable, the gradient descent algorithm doesn't change, you're just finding the minimum in a two dimensional space. \"Find the bottom of the parabola\" is the basic idea."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4a0c35c",
   "metadata": {},
   "source": [
    "## Ex6: Online Learning"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e927760",
   "metadata": {},
   "source": [
    "> **Exercise:** An extreme version of gradient descent is to use a mini-batch size of just 1. That is, given a training input, $x$, we update our weights and biases according to the rules ${w_k \\rightarrow w_k' = w_k - \\eta \\partial C_x / \\partial w_k}$ and ${b_l \\rightarrow b_l' = b_l - \\eta \\partial C_x / \\partial b_l}$. Then we choose another training input, and update the weights and biases again. And so on, repeatedly. This procedure is known as online, on-line, or incremental learning. In online learning, a neural network learns from just one training input at a time (just as human beings do). Name one advantage and one disadvantage of online learning, compared to stochastic gradient descent with a mini-batch size of, say, 20."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75a47759",
   "metadata": {},
   "source": [
    "\n",
    "Compared against stochastic gradient descent with a minibatch size of 20, online learning will better adjust to evolving trends in the data. On the other hand, it will handle outliers a lot worse.\n",
    "\n",
    "One way in which I personally look at gradient descent is through the lens of a digital filter. The [moving average](https://en.wikipedia.org/wiki/Moving_average) [low-pass filter](https://en.wikipedia.org/wiki/Low-pass_filter) is one of the simplest ways to \"smooth out\" a noisy signal. Generally speaking, the greater the number of samples in the signal you average together — i.e. the larger the window size — the smoother the signal gets. The smaller the window, the less smoothing/filtering is happening. With a window size of 1, well, there's no filtering happening at all. That means that spikes in the input get translated directly to the output.\n",
    "\n",
    "From a machine learning perspective, the minibatch size dictates the amount of filtering/smoothing that's going on. The smaller the minibatch size, the greater the impact of any outliers (\"noise\") on the model. It makes intuitive sense: if you have a million samples that are mostly clustered within some small space, and then a few massive outliers, those outliers will get smoothed/filtered out when their contribution to the error is averaged in with everything else.\n",
    "\n",
    "With a minibatch, this smoothing is reduced, but still present. With online learning, it isn't. Hence when the model encounters an outlier, it's likely to go wrong and stay wrong for a while — the number of good samples needed to get the model back on track will be directly proportional to the degree to which the outlier deviates from the rest."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ee2f736",
   "metadata": {},
   "source": [
    "## Ex7: Equivalence between equations 22 and 4"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4262d23",
   "metadata": {},
   "source": [
    "> **Exercise:** Write out Equation (22) in component form, and verify that it gives the same result as the rule (4) for computing the output of a sigmoid neuron."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19ca1cc0",
   "metadata": {},
   "source": [
    "$a' = \\sigma(w \\cdot a + b)$\n",
    "\n",
    "$a'_j = \\sigma(w_j \\cdot a + b_j)$\n",
    "\n",
    "$a'_j = \\sigma(\\sum_k w_{jk} a_k + b_j)$\n",
    "\n",
    "$a'_j = {1 / (1 + \\exp(-\\sum_k w_{jk} a_k - b_j))}$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a31ffb40",
   "metadata": {},
   "source": [
    "## Ex8: A two-layer neural network"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e082025c",
   "metadata": {},
   "source": [
    "> **Exercise:** Try creating a network with just two layers - an input and an output layer, no hidden layer - with 784 and 10 neurons, respectively. Train the network using stochastic gradient descent. What classification accuracy can you achieve?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0457f2a6",
   "metadata": {},
   "source": [
    "The code below is adapted from Michael's text to work with Python 3. After several runs, the best accuracy I could achieve was around 91%, although the figure bounced around wildly, with one run finishing at around 60-something percent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a1a7af1d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "5c8f2b25",
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = np.random.default_rng()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "79cb4ff0",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Network(object):\n",
    "  def __init__(self, sizes):\n",
    "    self.num_layers = len(sizes)\n",
    "    self.sizes = sizes\n",
    "    self.biases = [rng.standard_normal((y, 1)) for y in sizes[1:]]\n",
    "    self.weights = [rng.standard_normal((y, x)) for x,y in zip(sizes[:-1], sizes[1:])]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "6cce530e",
   "metadata": {},
   "outputs": [],
   "source": [
    "network = Network([3, 5, 4])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "3d30731b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 5, 4]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Raw input list of number of units in each layer\n",
    "network.sizes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "0c542b07",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[-1.07198418],\n",
       "        [ 0.33563292],\n",
       "        [-1.45178819],\n",
       "        [-1.28336643],\n",
       "        [ 0.03031064]]),\n",
       " array([[-0.08286307],\n",
       "        [ 0.14189407],\n",
       "        [ 0.25386069],\n",
       "        [ 1.13527978]])]"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Biases per layer, skipping the first layer which is input. Note that these are column vectors.\n",
    "network.biases"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "559b59f1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[-0.60291218,  0.94769696, -0.29207766],\n",
       "        [-0.49815986,  1.45154906,  0.86846283],\n",
       "        [ 0.7248065 , -0.78578538, -0.19009134],\n",
       "        [-0.42983594,  0.41917942,  0.81053381],\n",
       "        [ 0.70665528,  0.42502245,  1.11496938]]),\n",
       " array([[-0.28121247, -0.34703241, -1.56195391, -0.81001366, -1.28788254],\n",
       "        [-0.27383183,  0.06569628,  1.0284025 , -0.64158846, -0.92591406],\n",
       "        [-0.48960811, -0.12535807,  0.52961716,  0.94489982, -1.26546388],\n",
       "        [ 0.68333554, -0.3739202 , -0.38042004,  0.66598009, -0.01963056]])]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Matrices which take D units from previous layer and output N units.\n",
    "# So each layer is an NxD matrix.\n",
    "# N = Number of units in *this* layer.\n",
    "# D = Number of units in *previous* layer.\n",
    "# The zip trick in the constructor does this for us.\n",
    "network.weights"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "408554cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "mnist_loader\n",
    "~~~~~~~~~~~~\n",
    "\n",
    "A library to load the MNIST image data.  For details of the data\n",
    "structures that are returned, see the doc strings for ``load_data``\n",
    "and ``load_data_wrapper``.  In practice, ``load_data_wrapper`` is the\n",
    "function usually called by our neural network code.\n",
    "\"\"\"\n",
    "\n",
    "import pickle\n",
    "import gzip\n",
    "\n",
    "def load_data():\n",
    "    \"\"\"Return the MNIST data as a tuple containing the training data,\n",
    "    the validation data, and the test data.\n",
    "\n",
    "    The ``training_data`` is returned as a tuple with two entries.\n",
    "    The first entry contains the actual training images.  This is a\n",
    "    numpy ndarray with 50,000 entries.  Each entry is, in turn, a\n",
    "    numpy ndarray with 784 values, representing the 28 * 28 = 784\n",
    "    pixels in a single MNIST image.\n",
    "\n",
    "    The second entry in the ``training_data`` tuple is a numpy ndarray\n",
    "    containing 50,000 entries.  Those entries are just the digit\n",
    "    values (0...9) for the corresponding images contained in the first\n",
    "    entry of the tuple.\n",
    "\n",
    "    The ``validation_data`` and ``test_data`` are similar, except\n",
    "    each contains only 10,000 images.\n",
    "\n",
    "    This is a nice data format, but for use in neural networks it's\n",
    "    helpful to modify the format of the ``training_data`` a little.\n",
    "    That's done in the wrapper function ``load_data_wrapper()``, see\n",
    "    below.\n",
    "    \"\"\"\n",
    "    # mnist_modern.pkl.gz should work with modern Python, and is adapted from\n",
    "    # mnist.pkl.gz, which comes from:\n",
    "    #  https://github.com/MichalDanielDobrzanski/DeepLearningPython\n",
    "    # and is distributed under the MIT license.\n",
    "    with gzip.open('mnist_modern.pkl.gz', 'rb') as f:\n",
    "        data = np.load(f, allow_pickle=True, encoding='latin1')\n",
    "        training_data, validation_data, test_data = data\n",
    "    return (training_data, validation_data, test_data)\n",
    "\n",
    "def load_data_wrapper():\n",
    "    \"\"\"Return a tuple containing ``(training_data, validation_data,\n",
    "    test_data)``. Based on ``load_data``, but the format is more\n",
    "    convenient for use in our implementation of neural networks.\n",
    "\n",
    "    In particular, ``training_data`` is a list containing 50,000\n",
    "    2-tuples ``(x, y)``.  ``x`` is a 784-dimensional numpy.ndarray\n",
    "    containing the input image.  ``y`` is a 10-dimensional\n",
    "    numpy.ndarray representing the unit vector corresponding to the\n",
    "    correct digit for ``x``.\n",
    "\n",
    "    ``validation_data`` and ``test_data`` are lists containing 10,000\n",
    "    2-tuples ``(x, y)``.  In each case, ``x`` is a 784-dimensional\n",
    "    numpy.ndarry containing the input image, and ``y`` is the\n",
    "    corresponding classification, i.e., the digit values (integers)\n",
    "    corresponding to ``x``.\n",
    "\n",
    "    Obviously, this means we're using slightly different formats for\n",
    "    the training data and the validation / test data.  These formats\n",
    "    turn out to be the most convenient for use in our neural network\n",
    "    code.\"\"\"\n",
    "    tr_d, va_d, te_d = load_data()\n",
    "    training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]\n",
    "    training_results = [vectorized_result(y) for y in tr_d[1]]\n",
    "    training_data = list(zip(training_inputs, training_results)) # Convert to list\n",
    "    validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]\n",
    "    validation_data = list(zip(validation_inputs, va_d[1]))     # Convert to list\n",
    "    test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]\n",
    "    test_data = list(zip(test_inputs, te_d[1]))                 # Convert to list\n",
    "    return (training_data, validation_data, test_data)\n",
    "\n",
    "def vectorized_result(j):\n",
    "    \"\"\"Return a 10-dimensional unit vector with a 1.0 in the jth\n",
    "    position and zeroes elsewhere.  This is used to convert a digit\n",
    "    (0...9) into a corresponding desired output from the neural\n",
    "    network.\"\"\"\n",
    "    e = np.zeros((10, 1))\n",
    "    e[j] = 1.0\n",
    "    return e"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "daeec74a",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "network.py\n",
    "~~~~~~~~~~\n",
    "\n",
    "A module to implement the stochastic gradient descent learning\n",
    "algorithm for a feedforward neural network.  Gradients are calculated\n",
    "using backpropagation.  Note that I have focused on making the code\n",
    "simple, easily readable, and easily modifiable.  It is not optimized,\n",
    "and omits many desirable features.\n",
    "\"\"\"\n",
    "\n",
    "#### Libraries\n",
    "# Standard library\n",
    "import random\n",
    "\n",
    "class Network(object):\n",
    "\n",
    "    def __init__(self, sizes):\n",
    "        \"\"\"The list ``sizes`` contains the number of neurons in the\n",
    "        respective layers of the network.  For example, if the list\n",
    "        was [2, 3, 1] then it would be a three-layer network, with the\n",
    "        first layer containing 2 neurons, the second layer 3 neurons,\n",
    "        and the third layer 1 neuron.  The biases and weights for the\n",
    "        network are initialized randomly, using a Gaussian\n",
    "        distribution with mean 0, and variance 1.  Note that the first\n",
    "        layer is assumed to be an input layer, and by convention we\n",
    "        won't set any biases for those neurons, since biases are only\n",
    "        ever used in computing the outputs from later layers.\"\"\"\n",
    "        self.num_layers = len(sizes)\n",
    "        self.sizes = sizes\n",
    "        self.biases = [np.random.randn(y, 1) for y in sizes[1:]]\n",
    "        self.weights = [np.random.randn(y, x)\n",
    "                        for x, y in zip(sizes[:-1], sizes[1:])]\n",
    "\n",
    "    def feedforward(self, a):\n",
    "        \"\"\"Return the output of the network if ``a`` is input.\"\"\"\n",
    "        for b, w in zip(self.biases, self.weights):\n",
    "            a = sigmoid(np.dot(w, a)+b)\n",
    "        return a\n",
    "\n",
    "    def SGD(self, training_data, epochs, mini_batch_size, eta,\n",
    "            test_data=None):\n",
    "        \"\"\"Train the neural network using mini-batch stochastic\n",
    "        gradient descent.  The ``training_data`` is a list of tuples\n",
    "        ``(x, y)`` representing the training inputs and the desired\n",
    "        outputs.  The other non-optional parameters are\n",
    "        self-explanatory.  If ``test_data`` is provided then the\n",
    "        network will be evaluated against the test data after each\n",
    "        epoch, and partial progress printed out.  This is useful for\n",
    "        tracking progress, but slows things down substantially.\"\"\"\n",
    "        if test_data: n_test = len(test_data)\n",
    "        n = len(training_data)\n",
    "        for j in range(epochs):\n",
    "            random.shuffle(training_data)\n",
    "            mini_batches = [\n",
    "                training_data[k:k+mini_batch_size]\n",
    "                for k in range(0, n, mini_batch_size)]\n",
    "            for mini_batch in mini_batches:\n",
    "                self.update_mini_batch(mini_batch, eta)\n",
    "            if test_data:\n",
    "                print(\"Epoch {0}: {1} / {2}\".format(\n",
    "                    j, self.evaluate(test_data), n_test))\n",
    "            else:\n",
    "                print(\"Epoch {0} complete\".format(j))\n",
    "\n",
    "    def update_mini_batch(self, mini_batch, eta):\n",
    "        \"\"\"Update the network's weights and biases by applying\n",
    "        gradient descent using backpropagation to a single mini batch.\n",
    "        The ``mini_batch`` is a list of tuples ``(x, y)``, and ``eta``\n",
    "        is the learning rate.\"\"\"\n",
    "        nabla_b = [np.zeros(b.shape) for b in self.biases]\n",
    "        nabla_w = [np.zeros(w.shape) for w in self.weights]\n",
    "        for x, y in mini_batch:\n",
    "            delta_nabla_b, delta_nabla_w = self.backprop(x, y)\n",
    "            nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]\n",
    "            nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]\n",
    "        self.weights = [w-(eta/len(mini_batch))*nw\n",
    "                        for w, nw in zip(self.weights, nabla_w)]\n",
    "        self.biases = [b-(eta/len(mini_batch))*nb\n",
    "                       for b, nb in zip(self.biases, nabla_b)]\n",
    "\n",
    "    def backprop(self, x, y):\n",
    "        \"\"\"Return a tuple ``(nabla_b, nabla_w)`` representing the\n",
    "        gradient for the cost function C_x.  ``nabla_b`` and\n",
    "        ``nabla_w`` are layer-by-layer lists of numpy arrays, similar\n",
    "        to ``self.biases`` and ``self.weights``.\"\"\"\n",
    "        nabla_b = [np.zeros(b.shape) for b in self.biases]\n",
    "        nabla_w = [np.zeros(w.shape) for w in self.weights]\n",
    "        # feedforward\n",
    "        activation = x\n",
    "        activations = [x] # list to store all the activations, layer by layer\n",
    "        zs = [] # list to store all the z vectors, layer by layer\n",
    "        for b, w in zip(self.biases, self.weights):\n",
    "            z = np.dot(w, activation)+b\n",
    "            zs.append(z)\n",
    "            activation = sigmoid(z)\n",
    "            activations.append(activation)\n",
    "        # backward pass\n",
    "        delta = self.cost_derivative(activations[-1], y) * \\\n",
    "            sigmoid_prime(zs[-1])\n",
    "        nabla_b[-1] = delta\n",
    "        nabla_w[-1] = np.dot(delta, activations[-2].transpose())\n",
    "        # Note that the variable l in the loop below is used a little\n",
    "        # differently to the notation in Chapter 2 of the book.  Here,\n",
    "        # l = 1 means the last layer of neurons, l = 2 is the\n",
    "        # second-last layer, and so on.  It's a renumbering of the\n",
    "        # scheme in the book, used here to take advantage of the fact\n",
    "        # that Python can use negative indices in lists.\n",
    "        for l in range(2, self.num_layers):\n",
    "            z = zs[-l]\n",
    "            sp = sigmoid_prime(z)\n",
    "            delta = np.dot(self.weights[-l+1].transpose(), delta) * sp\n",
    "            nabla_b[-l] = delta\n",
    "            nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())\n",
    "        return (nabla_b, nabla_w)\n",
    "\n",
    "    def evaluate(self, test_data):\n",
    "        \"\"\"Return the number of test inputs for which the neural\n",
    "        network outputs the correct result. Note that the neural\n",
    "        network's output is assumed to be the index of whichever\n",
    "        neuron in the final layer has the highest activation.\"\"\"\n",
    "        test_results = [(np.argmax(self.feedforward(x)), y)\n",
    "                        for (x, y) in test_data]\n",
    "        return sum(int(x == y) for (x, y) in test_results)\n",
    "\n",
    "    def cost_derivative(self, output_activations, y):\n",
    "        \"\"\"Return the vector of partial derivatives for the output activations.\"\"\"\n",
    "        return (output_activations-y)\n",
    "\n",
    "#### Miscellaneous functions\n",
    "def sigmoid(z):\n",
    "    \"\"\"The sigmoid function.\"\"\"\n",
    "    return 1.0/(1.0+np.exp(-z))\n",
    "\n",
    "def sigmoid_prime(z):\n",
    "    \"\"\"Derivative of the sigmoid function.\"\"\"\n",
    "    return sigmoid(z)*(1-sigmoid(z))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "c94210ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "training_data, validation_data, test_data = load_data_wrapper()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "1d48a3ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "net = Network([784, 10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "6176e0b5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 0: 8411 / 10000\n",
      "Epoch 1: 8405 / 10000\n",
      "Epoch 2: 8421 / 10000\n",
      "Epoch 3: 8396 / 10000\n",
      "Epoch 4: 8398 / 10000\n",
      "Epoch 5: 8400 / 10000\n",
      "Epoch 6: 8427 / 10000\n",
      "Epoch 7: 8400 / 10000\n",
      "Epoch 8: 8418 / 10000\n",
      "Epoch 9: 8428 / 10000\n",
      "Epoch 10: 8419 / 10000\n",
      "Epoch 11: 8426 / 10000\n",
      "Epoch 12: 8418 / 10000\n",
      "Epoch 13: 8415 / 10000\n",
      "Epoch 14: 8429 / 10000\n",
      "Epoch 15: 8429 / 10000\n",
      "Epoch 16: 8400 / 10000\n",
      "Epoch 17: 8431 / 10000\n",
      "Epoch 18: 8411 / 10000\n",
      "Epoch 19: 8422 / 10000\n",
      "Epoch 20: 8419 / 10000\n",
      "Epoch 21: 8445 / 10000\n",
      "Epoch 22: 8421 / 10000\n",
      "Epoch 23: 8429 / 10000\n",
      "Epoch 24: 8422 / 10000\n",
      "Epoch 25: 8442 / 10000\n",
      "Epoch 26: 8429 / 10000\n",
      "Epoch 27: 8482 / 10000\n",
      "Epoch 28: 8463 / 10000\n",
      "Epoch 29: 8468 / 10000\n"
     ]
    }
   ],
   "source": [
    "net.SGD(training_data, 30, 10, 3.0, test_data=test_data)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "notebooks (3.14.3)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.14.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
