{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Training a Neural Network\n",
    "In this example, we'll be training a neural network using particle swarm optimization. For this we'll be using the standard global-best PSO `pyswarms.single.GBestPSO` for optimizing the network's weights and biases. This aims to demonstrate how the API is capable of handling custom-defined functions.\n",
    "\n",
    "For this example, we'll try to classify the three iris species in the Iris Dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import modules\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.datasets import load_iris\n",
    "\n",
    "\n",
    "# Import PySwarms\n",
    "import pyswarms as ps\n",
    "\n",
    "# Some more magic so that the notebook will reload external python modules;\n",
    "# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, we'll load the dataset from `scikit-learn`. The Iris Dataset contains 3 classes for each of the iris species (_iris setosa_, _iris virginica_, and _iris versicolor_). It has 50 samples per class with 150 samples in total, making it a very balanced dataset. Each sample is characterized by four features (or dimensions): sepal length, sepal width, petal length, petal width."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load the iris dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = load_iris()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Store the features as X and the labels as y\n",
    "X = data.data\n",
    "y = data.target"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Constructing a custom objective function\n",
    "Recall that neural networks can simply be seen as a mapping function from one space to another. For now, we'll build a simple neural network with the following characteristics:\n",
    "* Input layer size: 4\n",
    "* Hidden layer size: 20 (activation: $\\tanh(x)$)\n",
    "* Output layer size: 3 (activation: $softmax(x)$)\n",
    "\n",
    "Things we'll do:\n",
    "1. Create a `forward_prop` method that will do forward propagation for one particle.\n",
    "2. Create an overhead objective function `f()` that will compute `forward_prop()` for the whole swarm."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What we'll be doing then is to create a swarm with a number of dimensions equal to the weights and biases. We will __unroll__ these parameters into an n-dimensional array, and have each particle take on different values. Thus, each particle represents a candidate neural network with its own weights and bias. When feeding back to the network, we will reconstruct the learned weights and biases. \n",
    "\n",
    "When rolling-back the parameters into weights and biases, it is useful to recall the shape and bias matrices:\n",
    "* Shape of input-to-hidden weight matrix: (4, 20)\n",
    "* Shape of input-to-hidden bias array: (20, )\n",
    "* Shape of hidden-to-output weight matrix: (20, 3)\n",
    "* Shape of hidden-to-output bias array: (3, )\n",
    "\n",
    "By unrolling them together, we have $(4 * 20) + (20 * 3) + 20 + 3 = 163$ parameters, or 163 dimensions for each particle in the swarm.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The negative log-likelihood will be used to compute for the error between the ground-truth values and the predictions. Also, because PSO doesn't rely on the gradients, we'll not be performing backpropagation (this may be a good thing or bad thing under some circumstances).\n",
    "\n",
    "Now, let's write the forward propagation procedure as our objective function. Let $X$ be the input, $z_l$ the pre-activation at layer $l$, and $a_l$ the activation for layer $l$:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Neural network architecture"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "n_inputs = 4\n",
    "n_hidden = 20\n",
    "n_classes = 3\n",
    "\n",
    "num_samples = 150"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "def logits_function(p):\n",
    "    \"\"\" Calculate roll-back the weights and biases\n",
    "    \n",
    "    Inputs\n",
    "    ------\n",
    "    p: np.ndarray\n",
    "        The dimensions should include an unrolled version of the \n",
    "        weights and biases.\n",
    "    \n",
    "    Returns\n",
    "    -------\n",
    "    numpy.ndarray of logits for layer 2\n",
    "    \n",
    "    \"\"\"\n",
    "    # Roll-back the weights and biases\n",
    "    W1 = p[0:80].reshape((n_inputs,n_hidden))\n",
    "    b1 = p[80:100].reshape((n_hidden,))\n",
    "    W2 = p[100:160].reshape((n_hidden,n_classes))\n",
    "    b2 = p[160:163].reshape((n_classes,))\n",
    "    \n",
    "    # Perform forward propagation\n",
    "    z1 = X.dot(W1) + b1  # Pre-activation in Layer 1\n",
    "    a1 = np.tanh(z1)     # Activation in Layer 1\n",
    "    logits = a1.dot(W2) + b2 # Pre-activation in Layer 2\n",
    "    return logits          # Logits for Layer 2\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Forward propagation\n",
    "def forward_prop(params):\n",
    "    \"\"\"Forward propagation as objective function\n",
    "    \n",
    "    This computes for the forward propagation of the neural network, as\n",
    "    well as the loss. \n",
    "    \n",
    "    Inputs\n",
    "    ------\n",
    "    params: np.ndarray\n",
    "        The dimensions should include an unrolled version of the \n",
    "        weights and biases.\n",
    "        \n",
    "    Returns\n",
    "    -------\n",
    "    float\n",
    "        The computed negative log-likelihood loss given the parameters\n",
    "    \"\"\"\n",
    "    \n",
    "    logits = logits_function(params)\n",
    "    \n",
    "    # Compute for the softmax of the logits\n",
    "    exp_scores = np.exp(logits)\n",
    "    probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) \n",
    "    \n",
    "    # Compute for the negative log likelihood\n",
    "\n",
    "    corect_logprobs = -np.log(probs[range(num_samples), y])\n",
    "    loss = np.sum(corect_logprobs) / num_samples\n",
    "    \n",
    "    return loss\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have a method to do forward propagation for one particle (or for one set of dimensions), we can then create a higher-level method to compute `forward_prop()` to the whole swarm:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "def f(x):\n",
    "    \"\"\"Higher-level method to do forward_prop in the \n",
    "    whole swarm.\n",
    "    \n",
    "    Inputs\n",
    "    ------\n",
    "    x: numpy.ndarray of shape (n_particles, dimensions)\n",
    "        The swarm that will perform the search\n",
    "        \n",
    "    Returns\n",
    "    -------\n",
    "    numpy.ndarray of shape (n_particles, )\n",
    "        The computed loss for each particle\n",
    "    \"\"\"\n",
    "    n_particles = x.shape[0]\n",
    "    j = [forward_prop(x[i]) for i in range(n_particles)]\n",
    "    return np.array(j)\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Performing PSO on the custom-function\n",
    "Now that everything has been set-up, we just call our global-best PSO and run the optimizer as usual. For now, we'll just set the PSO parameters arbitrarily."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "# Initialize swarm\n",
    "options = {'c1': 0.5, 'c2': 0.3, 'w':0.9}\n",
    "\n",
    "# Call instance of PSO\n",
    "dimensions = (n_inputs * n_hidden) + (n_hidden * n_classes) + n_hidden + n_classes \n",
    "optimizer = ps.single.GlobalBestPSO(n_particles=100, dimensions=dimensions, options=options)\n",
    "\n",
    "# Perform optimization\n",
    "cost, pos = optimizer.optimize(f, iters=1000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Checking the accuracy\n",
    "We can then check the accuracy by performing forward propagation once again to create a set of predictions. Then it's only a simple matter of matching which one's correct or not. For the `logits`, we take the `argmax`. Recall that the softmax function returns probabilities where the whole vector sums to 1. We just take the one with the highest probability then treat it as the network's prediction.\n",
    "\n",
    "Moreover, we let the best position vector found by the swarm be the weight and bias parameters of the network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "def predict(pos):\n",
    "    \"\"\"\n",
    "    Use the trained weights to perform class predictions.\n",
    "    \n",
    "    Inputs\n",
    "    ------\n",
    "    pos: numpy.ndarray\n",
    "        Position matrix found by the swarm. Will be rolled\n",
    "        into weights and biases.\n",
    "    \"\"\"\n",
    "    logits = logits_function(pos)\n",
    "    y_pred = np.argmax(logits, axis=1)\n",
    "    return y_pred"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And from this we can just compute for the accuracy. We perform predictions, compare an equivalence to the ground-truth value `y`, and get the mean."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9866666666666667"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(predict(pos) == y).mean()"
   ]
  }
 ],
 "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.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
