{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Implementing the Gradient Descent Algorithm\n",
    "\n",
    "In this lab, we'll implement the basic functions of the Gradient Descent algorithm to find the boundary in a small dataset. First, we'll start with some functions that will help us plot and visualize the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "#Some helper functions for plotting and drawing lines\n",
    "\n",
    "def plot_points(X, y):\n",
    "    admitted = X[np.argwhere(y==1)]\n",
    "    rejected = X[np.argwhere(y==0)]\n",
    "    plt.scatter([s[0][0] for s in rejected], [s[0][1] for s in rejected], s = 25, color = 'blue', edgecolor = 'k')\n",
    "    plt.scatter([s[0][0] for s in admitted], [s[0][1] for s in admitted], s = 25, color = 'red', edgecolor = 'k')\n",
    "\n",
    "def display(m, b, color='g--'):\n",
    "    plt.xlim(-0.05,1.05)\n",
    "    plt.ylim(-0.05,1.05)\n",
    "    x = np.arange(-10, 10, 0.1)\n",
    "    plt.plot(x, m*x+b, color)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reading and plotting the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "data = pd.read_csv('data.csv', header=None)\n",
    "X = np.array(data[[0,1]])\n",
    "y = np.array(data[2])\n",
    "plot_points(X,y)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## TODO: Implementing the basic functions\n",
    "Here is your turn to shine. Implement the following formulas, as explained in the text.\n",
    "- Sigmoid activation function\n",
    "\n",
    "$$\\sigma(x) = \\frac{1}{1+e^{-x}}$$\n",
    "\n",
    "- Output (prediction) formula\n",
    "\n",
    "$$\\hat{y} = \\sigma(w_1 x_1 + w_2 x_2 + b)$$\n",
    "\n",
    "- Error function\n",
    "\n",
    "$$Error(y, \\hat{y}) = - y \\log(\\hat{y}) - (1-y) \\log(1-\\hat{y})$$\n",
    "\n",
    "- The function that updates the weights\n",
    "\n",
    "$$ w_i \\longrightarrow w_i + \\alpha (y - \\hat{y}) x_i$$\n",
    "\n",
    "$$ b \\longrightarrow b + \\alpha (y - \\hat{y})$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Implement the following functions\n",
    "\n",
    "# Activation (sigmoid) function\n",
    "def sigmoid(x):\n",
    "    pass\n",
    "\n",
    "# Output (prediction) formula\n",
    "def output_formula(features, weights, bias):\n",
    "    pass\n",
    "\n",
    "# Error (log-loss) formula\n",
    "def error_formula(y, output):\n",
    "    pass\n",
    "\n",
    "# Gradient descent step\n",
    "def update_weights(x, y, weights, bias, learnrate):\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training function\n",
    "This function will help us iterate the gradient descent algorithm through all the data, for a number of epochs. It will also plot the data, and some of the boundary lines obtained as we run the algorithm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "np.random.seed(44)\n",
    "\n",
    "epochs = 100\n",
    "learnrate = 0.01\n",
    "\n",
    "def train(features, targets, epochs, learnrate, graph_lines=False):\n",
    "    \n",
    "    errors = []\n",
    "    n_records, n_features = features.shape\n",
    "    last_loss = None\n",
    "    weights = np.random.normal(scale=1 / n_features**.5, size=n_features)\n",
    "    bias = 0\n",
    "    for e in range(epochs):\n",
    "        del_w = np.zeros(weights.shape)\n",
    "        for x, y in zip(features, targets):\n",
    "            output = output_formula(x, weights, bias)\n",
    "            error = error_formula(y, output)\n",
    "            weights, bias = update_weights(x, y, weights, bias, learnrate)\n",
    "        \n",
    "        # Printing out the log-loss error on the training set\n",
    "        out = output_formula(features, weights, bias)\n",
    "        loss = np.mean(error_formula(targets, out))\n",
    "        errors.append(loss)\n",
    "        if e % (epochs / 10) == 0:\n",
    "            print(\"\\n========== Epoch\", e,\"==========\")\n",
    "            if last_loss and last_loss < loss:\n",
    "                print(\"Train loss: \", loss, \"  WARNING - Loss Increasing\")\n",
    "            else:\n",
    "                print(\"Train loss: \", loss)\n",
    "            last_loss = loss\n",
    "            predictions = out > 0.5\n",
    "            accuracy = np.mean(predictions == targets)\n",
    "            print(\"Accuracy: \", accuracy)\n",
    "        if graph_lines and e % (epochs / 100) == 0:\n",
    "            display(-weights[0]/weights[1], -bias/weights[1])\n",
    "            \n",
    "\n",
    "    # Plotting the solution boundary\n",
    "    plt.title(\"Solution boundary\")\n",
    "    display(-weights[0]/weights[1], -bias/weights[1], 'black')\n",
    "\n",
    "    # Plotting the data\n",
    "    plot_points(features, targets)\n",
    "    plt.show()\n",
    "\n",
    "    # Plotting the error\n",
    "    plt.title(\"Error Plot\")\n",
    "    plt.xlabel('Number of epochs')\n",
    "    plt.ylabel('Error')\n",
    "    plt.plot(errors)\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Time to train the algorithm!\n",
    "When we run the function, we'll obtain the following:\n",
    "- 10 updates with the current training loss and accuracy\n",
    "- A plot of the data and some of the boundary lines obtained. The final one is in black. Notice how the lines get closer and closer to the best fit, as we go through more epochs.\n",
    "- A plot of the error function. Notice how it decreases as we go through more epochs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "train(X, y, epochs, learnrate, True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "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
}
