{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction to Deep Learning with PyTorch\n",
    "\n",
    "In this notebook, you'll get introduced to [PyTorch](http://pytorch.org/), a framework for building and training neural networks. PyTorch in a lot of ways behaves like the arrays you love from Numpy. These Numpy arrays, after all, are just tensors. PyTorch takes these tensors and makes it simple to move them to GPUs for the faster processing needed when training neural networks. It also provides a module that automatically calculates gradients (for backpropagation!) and another module specifically for building neural networks. All together, PyTorch ends up being more coherent with Python and the Numpy/Scipy stack compared to TensorFlow and other frameworks.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Neural Networks\n",
    "\n",
    "Deep Learning is based on artificial neural networks which have been around in some form since the late 1950s. The networks are built from individual parts approximating neurons, typically called units or simply \"neurons.\" Each unit has some number of weighted inputs. These weighted inputs are summed together (a linear combination) then passed through an activation function to get the unit's output.\n",
    "\n",
    "<img src=\"assets/simple_neuron.png\" width=400px>\n",
    "\n",
    "Mathematically this looks like: \n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "y &= f(w_1 x_1 + w_2 x_2 + b) \\\\\n",
    "y &= f\\left(\\sum_i w_i x_i +b \\right)\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "With vectors this is the dot/inner product of two vectors:\n",
    "\n",
    "$$\n",
    "h = \\begin{bmatrix}\n",
    "x_1 \\, x_2 \\cdots  x_n\n",
    "\\end{bmatrix}\n",
    "\\cdot \n",
    "\\begin{bmatrix}\n",
    "           w_1 \\\\\n",
    "           w_2 \\\\\n",
    "           \\vdots \\\\\n",
    "           w_n\n",
    "\\end{bmatrix}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tensors\n",
    "\n",
    "It turns out neural network computations are just a bunch of linear algebra operations on *tensors*, a generalization of matrices. A vector is a 1-dimensional tensor, a matrix is a 2-dimensional tensor, an array with three indices is a 3-dimensional tensor (RGB color images for example). The fundamental data structure for neural networks are tensors and PyTorch (as well as pretty much every other deep learning framework) is built around tensors.\n",
    "\n",
    "<img src=\"assets/tensor_examples.svg\" width=600px>\n",
    "\n",
    "With the basics covered, it's time to explore how we can use PyTorch to build a simple neural network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# First, import PyTorch\n",
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def activation(x):\n",
    "    \"\"\" Sigmoid activation function \n",
    "    \n",
    "        Arguments\n",
    "        ---------\n",
    "        x: torch.Tensor\n",
    "    \"\"\"\n",
    "    return 1/(1+torch.exp(-x))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Generate some data\n",
    "torch.manual_seed(7) # Set the random seed so things are predictable\n",
    "\n",
    "# Features are 3 random normal variables\n",
    "features = torch.randn((1, 5))\n",
    "# True weights for our data, random normal variables again\n",
    "weights = torch.randn_like(features)\n",
    "# and a true bias term\n",
    "bias = torch.randn((1, 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[-0.9179, -0.4578, -0.7245,  1.2799, -0.9941]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.randn_like(torch.randn((1, 5)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Above I generated data we can use to get the output of our simple network. This is all just random for now, going forward we'll start using normal data. Going through each relevant line:\n",
    "\n",
    "`features = torch.randn((1, 5))` creates a tensor with shape `(1, 5)`, one row and five columns, that contains values randomly distributed according to the normal distribution with a mean of zero and standard deviation of one. \n",
    "\n",
    "`weights = torch.randn_like(features)` creates another tensor with the same shape as `features`, again containing values from a normal distribution.\n",
    "\n",
    "Finally, `bias = torch.randn((1, 1))` creates a single value from a normal distribution.\n",
    "\n",
    "PyTorch tensors can be added, multiplied, subtracted, etc, just like Numpy arrays. In general, you'll use PyTorch tensors pretty much the same way you'd use Numpy arrays. They come with some nice benefits though such as GPU acceleration which we'll get to later. For now, use the generated data to calculate the output of this simple single layer network. \n",
    "> **Exercise**: Calculate the output of the network with input features `features`, weights `weights`, and bias `bias`. Similar to Numpy, PyTorch has a [`torch.sum()`](https://pytorch.org/docs/stable/torch.html#torch.sum) function, as well as a `.sum()` method on tensors, for taking sums. Use the function `activation` defined above as the activation function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[-1.6619]])\n"
     ]
    }
   ],
   "source": [
    "## Calculate the output of this network using the weights and bias tensors\n",
    "sum = torch.matmul(features, weights.view(5, 1)) + bias\n",
    "print(sum)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can do the multiplication and sum in the same operation using a matrix multiplication. In general, you'll want to use matrix multiplications since they are more efficient and accelerated using modern libraries and high-performance computing on GPUs.\n",
    "\n",
    "Here, we want to do a matrix multiplication of the features and the weights. For this we can use [`torch.mm()`](https://pytorch.org/docs/stable/torch.html#torch.mm) or [`torch.matmul()`](https://pytorch.org/docs/stable/torch.html#torch.matmul) which is somewhat more complicated and supports broadcasting. If we try to do it with `features` and `weights` as they are, we'll get an error\n",
    "\n",
    "```python\n",
    ">> torch.mm(features, weights)\n",
    "\n",
    "---------------------------------------------------------------------------\n",
    "RuntimeError                              Traceback (most recent call last)\n",
    "<ipython-input-13-15d592eb5279> in <module>()\n",
    "----> 1 torch.mm(features, weights)\n",
    "\n",
    "RuntimeError: size mismatch, m1: [1 x 5], m2: [1 x 5] at /Users/soumith/minicondabuild3/conda-bld/pytorch_1524590658547/work/aten/src/TH/generic/THTensorMath.c:2033\n",
    "```\n",
    "\n",
    "As you're building neural networks in any framework, you'll see this often. Really often. What's happening here is our tensors aren't the correct shapes to perform a matrix multiplication. Remember that for matrix multiplications, the number of columns in the first tensor must equal to the number of rows in the second column. Both `features` and `weights` have the same shape, `(1, 5)`. This means we need to change the shape of `weights` to get the matrix multiplication to work.\n",
    "\n",
    "**Note:** To see the shape of a tensor called `tensor`, use `tensor.shape`. If you're building neural networks, you'll be using this method often.\n",
    "\n",
    "There are a few options here: [`weights.reshape()`](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.reshape), [`weights.resize_()`](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.resize_), and [`weights.view()`](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.view).\n",
    "\n",
    "* `weights.reshape(a, b)` will return a new tensor with the same data as `weights` with size `(a, b)` sometimes, and sometimes a clone, as in it copies the data to another part of memory.\n",
    "* `weights.resize_(a, b)` returns the same tensor with a different shape. However, if the new shape results in fewer elements than the original tensor, some elements will be removed from the tensor (but not from memory). If the new shape results in more elements than the original tensor, new elements will be uninitialized in memory. Here I should note that the underscore at the end of the method denotes that this method is performed **in-place**. Here is a great forum thread to [read more about in-place operations](https://discuss.pytorch.org/t/what-is-in-place-operation/16244) in PyTorch.\n",
    "* `weights.view(a, b)` will return a new tensor with the same data as `weights` with size `(a, b)`.\n",
    "\n",
    "I usually use `.view()`, but any of the three methods will work for this. So, now we can reshape `weights` to have five rows and one column with something like `weights.view(5, 1)`.\n",
    "\n",
    "> **Exercise**: Calculate the output of our little network using matrix multiplication."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[ 0.1595]])\n"
     ]
    }
   ],
   "source": [
    "## Calculate the output of this y = activation(sum)\n",
    "y = activation(sum)\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Stack them up!\n",
    "\n",
    "That's how you can calculate the output for a single neuron. The real power of this algorithm happens when you start stacking these individual units into layers and stacks of layers, into a network of neurons. The output of one layer of neurons becomes the input for the next layer. With multiple input units and output units, we now need to express the weights as a matrix.\n",
    "\n",
    "<img src='assets/multilayer_diagram_weights.png' width=450px>\n",
    "\n",
    "The first layer shown on the bottom here are the inputs, understandably called the **input layer**. The middle layer is called the **hidden layer**, and the final layer (on the right) is the **output layer**. We can express this network mathematically with matrices again and use matrix multiplication to get linear combinations for each unit in one operation. For example, the hidden layer ($h_1$ and $h_2$ here) can be calculated \n",
    "\n",
    "$$\n",
    "\\vec{h} = [h_1 \\, h_2] = \n",
    "\\begin{bmatrix}\n",
    "x_1 \\, x_2 \\cdots \\, x_n\n",
    "\\end{bmatrix}\n",
    "\\cdot \n",
    "\\begin{bmatrix}\n",
    "           w_{11} & w_{12} \\\\\n",
    "           w_{21} &w_{22} \\\\\n",
    "           \\vdots &\\vdots \\\\\n",
    "           w_{n1} &w_{n2}\n",
    "\\end{bmatrix}\n",
    "$$\n",
    "\n",
    "The output for this small network is found by treating the hidden layer as inputs for the output unit. The network output is expressed simply\n",
    "\n",
    "$$\n",
    "y =  f_2 \\! \\left(\\, f_1 \\! \\left(\\vec{x} \\, \\mathbf{W_1}\\right) \\mathbf{W_2} \\right)\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Generate some data\n",
    "torch.manual_seed(7) # Set the random seed so things are predictable\n",
    "\n",
    "# Features are 3 random normal variables\n",
    "features = torch.randn((1, 3))\n",
    "\n",
    "# Define the size of each layer in our network\n",
    "n_input = features.shape[1]     # Number of input units, must match number of input features\n",
    "n_hidden = 2                    # Number of hidden units \n",
    "n_output = 1                    # Number of output units\n",
    "\n",
    "# Weights for inputs to hidden layer\n",
    "W1 = torch.randn(n_input, n_hidden)\n",
    "# Weights for hidden layer to output layer\n",
    "W2 = torch.randn(n_hidden, n_output)\n",
    "\n",
    "# and bias terms for hidden and output layers\n",
    "B1 = torch.randn((1, n_hidden))\n",
    "B2 = torch.randn((1, n_output))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> **Exercise:** Calculate the output for this multi-layer network using the weights `W1` & `W2`, and the biases, `B1` & `B2`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[ 0.3171]])\n"
     ]
    }
   ],
   "source": [
    "## Your solution here\n",
    "h = torch.mm(features, W1) + B1\n",
    "h = activation(h)\n",
    "output = torch.mm(h, W2) + B2\n",
    "output = activation(output)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you did this correctly, you should see the output `tensor([[ 0.3171]])`.\n",
    "\n",
    "The number of hidden units a parameter of the network, often called a **hyperparameter** to differentiate it from the weights and biases parameters. As you'll see later when we discuss training a neural network, the more hidden units a network has, and the more layers, the better able it is to learn from data and make accurate predictions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Numpy to Torch and back\n",
    "\n",
    "Special bonus section! PyTorch has a great feature for converting between Numpy arrays and Torch tensors. To create a tensor from a Numpy array, use `torch.from_numpy()`. To convert a tensor to a Numpy array, use the `.numpy()` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.25916044,  0.07974115,  0.13661261],\n",
       "       [ 0.12537927,  0.68318453,  0.24728824],\n",
       "       [ 0.49867652,  0.62760544,  0.84363415],\n",
       "       [ 0.39216351,  0.87075396,  0.0653991 ]])"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "a = np.random.rand(4,3)\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0.2592,  0.0797,  0.1366],\n",
       "        [ 0.1254,  0.6832,  0.2473],\n",
       "        [ 0.4987,  0.6276,  0.8436],\n",
       "        [ 0.3922,  0.8708,  0.0654]], dtype=torch.float64)"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b = torch.from_numpy(a)\n",
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.25916044,  0.07974115,  0.13661261],\n",
       "       [ 0.12537927,  0.68318453,  0.24728824],\n",
       "       [ 0.49867652,  0.62760544,  0.84363415],\n",
       "       [ 0.39216351,  0.87075396,  0.0653991 ]])"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b.numpy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The memory is shared between the Numpy array and Torch tensor, so if you change the values in-place of one object, the other will change as well."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0.5183,  0.1595,  0.2732],\n",
       "        [ 0.2508,  1.3664,  0.4946],\n",
       "        [ 0.9974,  1.2552,  1.6873],\n",
       "        [ 0.7843,  1.7415,  0.1308]], dtype=torch.float64)"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Multiply PyTorch Tensor by 2, in place\n",
    "b.mul_(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.51832089,  0.15948231,  0.27322523],\n",
       "       [ 0.25075854,  1.36636907,  0.49457648],\n",
       "       [ 0.99735305,  1.25521088,  1.68726831],\n",
       "       [ 0.78432703,  1.74150792,  0.1307982 ]])"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Numpy array matches new values from Tensor\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
