{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Your very own neural network\n",
    "\n",
    "In this notebook, we're going to build a neural network using naught but pure numpy and steel nerves. It's going to be fun, I promise!\n",
    "\n",
    "![img](https://s27.postimg.org/vpui4r5n7/cartoon-2029952_960_720.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# use the preloaded keras datasets and models\n",
    "! mkdir -p ~/.keras/datasets\n",
    "! mkdir -p ~/.keras/models\n",
    "! ln -s $(realpath ../readonly/keras/datasets/*) ~/.keras/datasets/\n",
    "! ln -s $(realpath ../readonly/keras/models/*) ~/.keras/models/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "import numpy as np\n",
    "np.random.seed(42)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here goes our main class: a layer that can .forward() and .backward()."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Layer:\n",
    "    \"\"\"\n",
    "    A building block. Each layer is capable of performing two things:\n",
    "    \n",
    "    - Process input to get output:           output = layer.forward(input)\n",
    "    \n",
    "    - Propagate gradients through itself:    grad_input = layer.backward(input, grad_output)\n",
    "    \n",
    "    Some layers also have learnable parameters which they update during layer.backward.\n",
    "    \"\"\"\n",
    "    def __init__(self):\n",
    "        \"\"\"Here you can initialize layer parameters (if any) and auxiliary stuff.\"\"\"\n",
    "        # A dummy layer does nothing\n",
    "        pass\n",
    "    \n",
    "    def forward(self, input):\n",
    "        \"\"\"\n",
    "        Takes input data of shape [batch, input_units], returns output data [batch, output_units]\n",
    "        \"\"\"\n",
    "        # A dummy layer just returns whatever it gets as input.\n",
    "        return input\n",
    "\n",
    "    def backward(self, input, grad_output):\n",
    "        \"\"\"\n",
    "        Performs a backpropagation step through the layer, with respect to the given input.\n",
    "        \n",
    "        To compute loss gradients w.r.t input, you need to apply chain rule (backprop):\n",
    "        \n",
    "        d loss / d x  = (d loss / d layer) * (d layer / d x)\n",
    "        \n",
    "        Luckily, you already receive d loss / d layer as input, so you only need to multiply it by d layer / d x.\n",
    "        \n",
    "        If your layer has parameters (e.g. dense layer), you also need to update them here using d loss / d layer\n",
    "        \"\"\"\n",
    "        # The gradient of a dummy layer is precisely grad_output, but we'll write it more explicitly\n",
    "        num_units = input.shape[1]\n",
    "        \n",
    "        d_layer_d_input = np.eye(num_units)\n",
    "        \n",
    "        return np.dot(grad_output, d_layer_d_input) # chain rule"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The road ahead\n",
    "\n",
    "We're going to build a neural network that classifies MNIST digits. To do so, we'll need a few building blocks:\n",
    "- Dense layer - a fully-connected layer, $f(X)=W \\cdot X + \\vec{b}$\n",
    "- ReLU layer (or any other nonlinearity you want)\n",
    "- Loss function - crossentropy\n",
    "- Backprop algorithm - a stochastic gradient descent with backpropageted gradients\n",
    "\n",
    "Let's approach them one at a time.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Nonlinearity layer\n",
    "\n",
    "This is the simplest layer you can get: it simply applies a nonlinearity to each element of your network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class ReLU(Layer):\n",
    "    def __init__(self):\n",
    "        \"\"\"ReLU layer simply applies elementwise rectified linear unit to all inputs\"\"\"\n",
    "        pass\n",
    "    \n",
    "    def forward(self, input):\n",
    "        \"\"\"Apply elementwise ReLU to [batch, input_units] matrix\"\"\"\n",
    "        # <your code. Try np.maximum>\n",
    "    \n",
    "    def backward(self, input, grad_output):\n",
    "        \"\"\"Compute gradient of loss w.r.t. ReLU input\"\"\"\n",
    "        relu_grad = input > 0\n",
    "        return grad_output*relu_grad        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# some tests\n",
    "from util import eval_numerical_gradient\n",
    "x = np.linspace(-1,1,10*32).reshape([10,32])\n",
    "l = ReLU()\n",
    "grads = l.backward(x,np.ones([10,32])/(32*10))\n",
    "numeric_grads = eval_numerical_gradient(lambda x: l.forward(x).mean(), x=x)\n",
    "assert np.allclose(grads, numeric_grads, rtol=1e-3, atol=0),\\\n",
    "    \"gradient returned by your layer does not match the numerically computed gradient\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Instant primer: lambda functions\n",
    "\n",
    "In python, you can define functions in one line using the `lambda` syntax: `lambda param1, param2: expression`\n",
    "\n",
    "For example: `f = lambda x, y: x+y` is equivalent to a normal function:\n",
    "\n",
    "```\n",
    "def f(x,y):\n",
    "    return x+y\n",
    "```\n",
    "For more information, click [here](http://www.secnetix.de/olli/Python/lambda_functions.hawk).    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dense layer\n",
    "\n",
    "Now let's build something more complicated. Unlike nonlinearity, a dense layer actually has something to learn.\n",
    "\n",
    "A dense layer applies affine transformation. In a vectorized form, it can be described as:\n",
    "$$f(X)= W \\cdot X + \\vec b $$\n",
    "\n",
    "Where \n",
    "* X is an object-feature matrix of shape [batch_size, num_features],\n",
    "* W is a weight matrix [num_features, num_outputs] \n",
    "* and b is a vector of num_outputs biases.\n",
    "\n",
    "Both W and b are initialized during layer creation and updated each time backward is called."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Dense(Layer):\n",
    "    def __init__(self, input_units, output_units, learning_rate=0.1):\n",
    "        \"\"\"\n",
    "        A dense layer is a layer which performs a learned affine transformation:\n",
    "        f(x) = <W*x> + b\n",
    "        \"\"\"\n",
    "        self.learning_rate = learning_rate\n",
    "        \n",
    "        # initialize weights with small random numbers. We use normal initialization, \n",
    "        # but surely there is something better. Try this once you got it working: http://bit.ly/2vTlmaJ\n",
    "        self.weights = np.random.randn(input_units, output_units)*0.01\n",
    "        self.biases = np.zeros(output_units)\n",
    "        \n",
    "    def forward(self,input):\n",
    "        \"\"\"\n",
    "        Perform an affine transformation:\n",
    "        f(x) = <W*x> + b\n",
    "        \n",
    "        input shape: [batch, input_units]\n",
    "        output shape: [batch, output units]\n",
    "        \"\"\"\n",
    "        return #<your code here>\n",
    "    \n",
    "    def backward(self,input,grad_output):\n",
    "        \n",
    "        # compute d f / d x = d f / d dense * d dense / d x\n",
    "        # where d dense/ d x = weights transposed\n",
    "        grad_input = #<your code here>\n",
    "        \n",
    "        # compute gradient w.r.t. weights and biases\n",
    "        grad_weights = #<your code here>\n",
    "        grad_biases = #<your code here>\n",
    "        \n",
    "        assert grad_weights.shape == self.weights.shape and grad_biases.shape == self.biases.shape\n",
    "        # Here we perform a stochastic gradient descent step. \n",
    "        # Later on, you can try replacing that with something better.\n",
    "        self.weights = self.weights - self.learning_rate * grad_weights\n",
    "        self.biases = self.biases - self.learning_rate * grad_biases\n",
    "        \n",
    "        return grad_input"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Testing the dense layer\n",
    "\n",
    "Here we have a few tests to make sure your dense layer works properly. You can just run them, get 3 \"well done\"s and forget they ever existed.\n",
    "\n",
    "... or not get 3 \"well done\"s and go fix stuff. If that is the case, here are some tips for you:\n",
    "* Make sure you compute gradients for W and b as __sum of gradients over batch__, not mean over gradients. Grad_output is already divided by batch size.\n",
    "* If you're debugging, try saving gradients in class fields, like \"self.grad_w = grad_w\" or print first 3-5 weights. This helps debugging.\n",
    "* If nothing else helps, try ignoring tests and proceed to network training. If it trains alright, you may be off by something that does not affect network training."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Well done!\n"
     ]
    }
   ],
   "source": [
    "l = Dense(128, 150)\n",
    "\n",
    "assert -0.05 < l.weights.mean() < 0.05 and 1e-3 < l.weights.std() < 1e-1,\\\n",
    "    \"The initial weights must have zero mean and small variance. \"\\\n",
    "    \"If you know what you're doing, remove this assertion.\"\n",
    "assert -0.05 < l.biases.mean() < 0.05, \"Biases must be zero mean. Ignore if you have a reason to do otherwise.\"\n",
    "\n",
    "# To test the outputs, we explicitly set weights with fixed values. DO NOT DO THAT IN ACTUAL NETWORK!\n",
    "l = Dense(3,4)\n",
    "\n",
    "x = np.linspace(-1,1,2*3).reshape([2,3])\n",
    "l.weights = np.linspace(-1,1,3*4).reshape([3,4])\n",
    "l.biases = np.linspace(-1,1,4)\n",
    "\n",
    "assert np.allclose(l.forward(x),np.array([[ 0.07272727,  0.41212121,  0.75151515,  1.09090909],\n",
    "                                          [-0.90909091,  0.08484848,  1.07878788,  2.07272727]]))\n",
    "print(\"Well done!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Well done!\n"
     ]
    }
   ],
   "source": [
    "# To test the grads, we use gradients obtained via finite differences\n",
    "\n",
    "from util import eval_numerical_gradient\n",
    "\n",
    "x = np.linspace(-1,1,10*32).reshape([10,32])\n",
    "l = Dense(32,64,learning_rate=0)\n",
    "\n",
    "numeric_grads = eval_numerical_gradient(lambda x: l.forward(x).sum(),x)\n",
    "grads = l.backward(x,np.ones([10,64]))\n",
    "\n",
    "assert np.allclose(grads,numeric_grads,rtol=1e-3,atol=0), \"input gradient does not match numeric grad\"\n",
    "print(\"Well done!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Well done!\n"
     ]
    }
   ],
   "source": [
    "#test gradients w.r.t. params\n",
    "def compute_out_given_wb(w,b):\n",
    "    l = Dense(32,64,learning_rate=1)\n",
    "    l.weights = np.array(w)\n",
    "    l.biases = np.array(b)\n",
    "    x = np.linspace(-1,1,10*32).reshape([10,32])\n",
    "    return l.forward(x)\n",
    "    \n",
    "def compute_grad_by_params(w,b):\n",
    "    l = Dense(32,64,learning_rate=1)\n",
    "    l.weights = np.array(w)\n",
    "    l.biases = np.array(b)\n",
    "    x = np.linspace(-1,1,10*32).reshape([10,32])\n",
    "    l.backward(x,np.ones([10,64]) / 10.)\n",
    "    return w - l.weights, b - l.biases\n",
    "    \n",
    "w,b = np.random.randn(32,64), np.linspace(-1,1,64)\n",
    "\n",
    "numeric_dw = eval_numerical_gradient(lambda w: compute_out_given_wb(w,b).mean(0).sum(),w )\n",
    "numeric_db = eval_numerical_gradient(lambda b: compute_out_given_wb(w,b).mean(0).sum(),b )\n",
    "grad_w,grad_b = compute_grad_by_params(w,b)\n",
    "\n",
    "assert np.allclose(numeric_dw,grad_w,rtol=1e-3,atol=0), \"weight gradient does not match numeric weight gradient\"\n",
    "assert np.allclose(numeric_db,grad_b,rtol=1e-3,atol=0), \"weight gradient does not match numeric weight gradient\"\n",
    "print(\"Well done!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The loss function\n",
    "\n",
    "Since we want to predict probabilities, it would be logical for us to define softmax nonlinearity on top of our network and compute loss given predicted probabilities. However, there is a better way to do so.\n",
    "\n",
    "If you write down the expression for crossentropy as a function of softmax logits (a), you'll see:\n",
    "\n",
    "$$ loss = - log \\space {e^{a_{correct}} \\over {\\underset i \\sum e^{a_i} } } $$\n",
    "\n",
    "If you take a closer look, ya'll see that it can be rewritten as:\n",
    "\n",
    "$$ loss = - a_{correct} + log {\\underset i \\sum e^{a_i} } $$\n",
    "\n",
    "It's called Log-softmax and it's better than naive log(softmax(a)) in all aspects:\n",
    "* Better numerical stability\n",
    "* Easier to get derivative right\n",
    "* Marginally faster to compute\n",
    "\n",
    "So why not just use log-softmax throughout our computation and never actually bother to estimate probabilities.\n",
    "\n",
    "Here you are! We've defined the both loss functions for you so that you could focus on neural network part."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def softmax_crossentropy_with_logits(logits,reference_answers):\n",
    "    \"\"\"Compute crossentropy from logits[batch,n_classes] and ids of correct answers\"\"\"\n",
    "    logits_for_answers = logits[np.arange(len(logits)),reference_answers]\n",
    "    \n",
    "    xentropy = - logits_for_answers + np.log(np.sum(np.exp(logits),axis=-1))\n",
    "    \n",
    "    return xentropy\n",
    "\n",
    "def grad_softmax_crossentropy_with_logits(logits,reference_answers):\n",
    "    \"\"\"Compute crossentropy gradient from logits[batch,n_classes] and ids of correct answers\"\"\"\n",
    "    ones_for_answers = np.zeros_like(logits)\n",
    "    ones_for_answers[np.arange(len(logits)),reference_answers] = 1\n",
    "    \n",
    "    softmax = np.exp(logits) / np.exp(logits).sum(axis=-1,keepdims=True)\n",
    "    \n",
    "    return (- ones_for_answers + softmax) / logits.shape[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "logits = np.linspace(-1,1,500).reshape([50,10])\n",
    "answers = np.arange(50)%10\n",
    "\n",
    "softmax_crossentropy_with_logits(logits,answers)\n",
    "grads = grad_softmax_crossentropy_with_logits(logits,answers)\n",
    "numeric_grads = eval_numerical_gradient(lambda l: softmax_crossentropy_with_logits(l,answers).mean(),logits)\n",
    "\n",
    "assert np.allclose(numeric_grads,grads,rtol=1e-3,atol=0), \"The reference implementation has just failed. Someone has just changed the rules of math.\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Full network\n",
    "\n",
    "Now let's combine what we've just built into a working neural network. As we announced, we're gonna use this monster to classify handwritten digits, so let's get them loaded."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    },
    {
     "data": {
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PrBJsU/HKqu1C78T8yIrNFrn7kLqsvEaabZuabXuK\n0Ix/ZmxT4+IQCgAkigYOAImqZwOfWsd110qzbVOzbU8RmvHPjG1qUHU7Bg4AqA6HUAAgUYU3cDM7\n2syWm9krZnZh0evPQ/ag23VmtqRFrIeZPWRmL2c/k3oQrpntY2YLzGypmb1gZudk8aS3q0jUdmNq\n5toutIGbWVdJN0r6uqRBksaZ2aAic8jJdElHt4pdKGm+uw+QND/7nJLNks5z90GShkk6O/u7SX27\nCkFtN7Smre2i98CHSnrF3V919w8l3S3puIJzqJq7Pybp7Vbh4yTNyN7PkDSm0KSq5O5r3P2Z7P1G\nScsk9VHi21UgartBNXNtF93A+0j6a4vPq7JYM+jV4rmJr0vqVc9kqpE9if0QSQvVRNtVY9R2Apqt\ntjmJWQNeurQnyct7zGxXSbMlnevuG1p+l/J2IR8p10Az1nbRDXy1pH1afO6bxZrBWjPrLUnZz3V1\nzqfDzKybSgV+p7v/Jgsnv10FobYbWLPWdtEN/ClJA8xsPzPrLuk7kuYVnEOtzJM0IXs/QdLcOubS\nYWZmkm6TtMzdr2nxVdLbVSBqu0E1c20XfiOPmY2W9AtJXSVNc/fLC00gB2Z2l6QRKo1otlbSJZJ+\nK+lXkvqpNCrdWHdvfTKoYZnZcEl/lPS8pK1Z+CKVjhUmu11ForYbUzPXNndiAkCiOIkJAImigQNA\nomjgAJAoGjgAJIoGDgCJooEDQKJo4ACQKBo4ACTq/wMOa0tS7dporAAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7f584c14da20>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "from preprocessed_mnist import load_dataset\n",
    "X_train, y_train, X_val, y_val, X_test, y_test = load_dataset(flatten=True)\n",
    "\n",
    "plt.figure(figsize=[6,6])\n",
    "for i in range(4):\n",
    "    plt.subplot(2,2,i+1)\n",
    "    plt.title(\"Label: %i\"%y_train[i])\n",
    "    plt.imshow(X_train[i].reshape([28,28]),cmap='gray');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll define network as a list of layers, each applied on top of previous one. In this setting, computing predictions and training becomes trivial."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "network = []\n",
    "network.append(Dense(X_train.shape[1],100))\n",
    "network.append(ReLU())\n",
    "network.append(Dense(100,200))\n",
    "network.append(ReLU())\n",
    "network.append(Dense(200,10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def forward(network, X):\n",
    "    \"\"\"\n",
    "    Compute activations of all network layers by applying them sequentially.\n",
    "    Return a list of activations for each layer. \n",
    "    Make sure last activation corresponds to network logits.\n",
    "    \"\"\"\n",
    "    activations = []\n",
    "    input = X\n",
    "\n",
    "    # <your code here>\n",
    "        \n",
    "    assert len(activations) == len(network)\n",
    "    return activations\n",
    "\n",
    "def predict(network,X):\n",
    "    \"\"\"\n",
    "    Compute network predictions.\n",
    "    \"\"\"\n",
    "    logits = forward(network,X)[-1]\n",
    "    return logits.argmax(axis=-1)\n",
    "\n",
    "def train(network,X,y):\n",
    "    \"\"\"\n",
    "    Train your network on a given batch of X and y.\n",
    "    You first need to run forward to get all layer activations.\n",
    "    Then you can run layer.backward going from last to first layer.\n",
    "    \n",
    "    After you called backward for all layers, all Dense layers have already made one gradient step.\n",
    "    \"\"\"\n",
    "    \n",
    "    # Get the layer activations\n",
    "    layer_activations = forward(network,X)\n",
    "    layer_inputs = [X]+layer_activations  #layer_input[i] is an input for network[i]\n",
    "    logits = layer_activations[-1]\n",
    "    \n",
    "    # Compute the loss and the initial gradient\n",
    "    loss = softmax_crossentropy_with_logits(logits,y)\n",
    "    loss_grad = grad_softmax_crossentropy_with_logits(logits,y)\n",
    "    \n",
    "    # <your code: propagate gradients through the network>\n",
    "        \n",
    "    return np.mean(loss)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Instead of tests, we provide you with a training loop that prints training and validation accuracies on every epoch.\n",
    "\n",
    "If your implementation of forward and backward are correct, your accuracy should grow from 90~93% to >97% with the default network."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training loop\n",
    "\n",
    "As usual, we split data into minibatches, feed each such minibatch into the network and update weights."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from tqdm import trange\n",
    "def iterate_minibatches(inputs, targets, batchsize, shuffle=False):\n",
    "    assert len(inputs) == len(targets)\n",
    "    if shuffle:\n",
    "        indices = np.random.permutation(len(inputs))\n",
    "    for start_idx in trange(0, len(inputs) - batchsize + 1, batchsize):\n",
    "        if shuffle:\n",
    "            excerpt = indices[start_idx:start_idx + batchsize]\n",
    "        else:\n",
    "            excerpt = slice(start_idx, start_idx + batchsize)\n",
    "        yield inputs[excerpt], targets[excerpt]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from IPython.display import clear_output\n",
    "train_log = []\n",
    "val_log = []"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "for epoch in range(25):\n",
    "\n",
    "    for x_batch,y_batch in iterate_minibatches(X_train,y_train,batchsize=32,shuffle=True):\n",
    "        train(network,x_batch,y_batch)\n",
    "    \n",
    "    train_log.append(np.mean(predict(network,X_train)==y_train))\n",
    "    val_log.append(np.mean(predict(network,X_val)==y_val))\n",
    "    \n",
    "    clear_output()\n",
    "    print(\"Epoch\",epoch)\n",
    "    print(\"Train accuracy:\",train_log[-1])\n",
    "    print(\"Val accuracy:\",val_log[-1])\n",
    "    plt.plot(train_log,label='train accuracy')\n",
    "    plt.plot(val_log,label='val accuracy')\n",
    "    plt.legend(loc='best')\n",
    "    plt.grid()\n",
    "    plt.show()\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Peer-reviewed assignment\n",
    "\n",
    "Congradulations, you managed to get this far! There is just one quest left undone, and this time you'll get to choose what to do.\n",
    "\n",
    "\n",
    "#### Option I: initialization\n",
    "* Implement Dense layer with Xavier initialization as explained [here](http://bit.ly/2vTlmaJ)\n",
    "\n",
    "To pass this assignment, you must conduct an experiment showing how xavier initialization compares to default initialization on deep networks (5+ layers).\n",
    "\n",
    "\n",
    "#### Option II: regularization\n",
    "* Implement a version of Dense layer with L2 regularization penalty: when updating Dense Layer weights, adjust gradients to minimize\n",
    "\n",
    "$$ Loss = Crossentropy + \\alpha \\cdot \\underset i \\sum {w_i}^2 $$\n",
    "\n",
    "To pass this assignment, you must conduct an experiment showing if regularization mitigates overfitting in case of abundantly large number of neurons. Consider tuning $\\alpha$ for better results.\n",
    "\n",
    "#### Option III: optimization\n",
    "* Implement a version of Dense layer that uses momentum/rmsprop or whatever method worked best for you last time.\n",
    "\n",
    "Most of those methods require persistent parameters like momentum direction or moving average grad norm, but you can easily store those params inside your layers.\n",
    "\n",
    "To pass this assignment, you must conduct an experiment showing how your chosen method performs compared to vanilla SGD.\n",
    "\n",
    "### General remarks\n",
    "_Please read the peer-review guidelines before starting this part of the assignment._\n",
    "\n",
    "In short, a good solution is one that:\n",
    "* is based on this notebook\n",
    "* runs in the default course environment with Run All\n",
    "* its code doesn't cause spontaneous eye bleeding\n",
    "* its report is easy to read.\n",
    "\n",
    "_Formally we can't ban you from writing boring reports, but if you bored your reviewer to death, there's noone left alive to give you the grade you want._\n",
    "\n",
    "\n",
    "### Bonus assignments\n",
    "\n",
    "As a bonus assignment (no points, just swag), consider implementing Batch Normalization ([guide](https://gab41.lab41.org/batch-normalization-what-the-hey-d480039a9e3b)) or Dropout ([guide](https://medium.com/@amarbudhiraja/https-medium-com-amarbudhiraja-learning-less-to-learn-better-dropout-in-deep-machine-learning-74334da4bfc5)). Note, however, that those \"layers\" behave differently when training and when predicting on test set.\n",
    "\n",
    "* Dropout:\n",
    "  * During training: drop units randomly with probability __p__ and multiply everything by __1/(1-p)__\n",
    "  * During final predicton: do nothing; pretend there's no dropout\n",
    "  \n",
    "* Batch normalization\n",
    "  * During training, it substracts mean-over-batch and divides by std-over-batch and updates mean and variance.\n",
    "  * During final prediction, it uses accumulated mean and variance.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 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.6.0"
  },
  "toc": {
   "colors": {
    "hover_highlight": "#DAA520",
    "navigate_num": "#000000",
    "navigate_text": "#333333",
    "running_highlight": "#FF0000",
    "selected_highlight": "#FFD700",
    "sidebar_border": "#EEEEEE",
    "wrapper_background": "#FFFFFF"
   },
   "moveMenuLeft": true,
   "nav_menu": {
    "height": "264px",
    "width": "252px"
   },
   "navigate_menu": true,
   "number_sections": true,
   "sideBar": true,
   "threshold": 4,
   "toc_cell": false,
   "toc_section_display": "block",
   "toc_window_display": false,
   "widenNotebook": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
