941 lines
46 KiB
Plaintext
Executable File
941 lines
46 KiB
Plaintext
Executable File
{
|
||
"cells": [
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"# Programming Exercise 4: Neural Networks Learning\n",
|
||
"\n",
|
||
"## Introduction\n",
|
||
"\n",
|
||
"In this exercise, you will implement the backpropagation algorithm for neural networks and apply it to the task of hand-written digit recognition. Before starting on the programming exercise, we strongly recommend watching the video lectures and completing the review questions for the associated topics.\n",
|
||
"\n",
|
||
"\n",
|
||
"All the information you need for solving this assignment is in this notebook, and all the code you will be implementing will take place within this notebook. The assignment can be promptly submitted to the coursera grader directly from this notebook (code and instructions are included below).\n",
|
||
"\n",
|
||
"Before we begin with the exercises, we need to import all libraries required for this programming exercise. Throughout the course, we will be using [`numpy`](http://www.numpy.org/) for all arrays and matrix operations, [`matplotlib`](https://matplotlib.org/) for plotting, and [`scipy`](https://docs.scipy.org/doc/scipy/reference/) for scientific and numerical computation functions and tools. You can find instructions on how to install required libraries in the README file in the [github repository](https://github.com/dibgerge/ml-coursera-python-assignments)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# used for manipulating directory paths\n",
|
||
"import os\n",
|
||
"\n",
|
||
"# Scientific and vector computation for python\n",
|
||
"import numpy as np\n",
|
||
"\n",
|
||
"# Plotting library\n",
|
||
"from matplotlib import pyplot\n",
|
||
"\n",
|
||
"# Optimization module in scipy\n",
|
||
"from scipy import optimize\n",
|
||
"\n",
|
||
"# will be used to load MATLAB mat datafile format\n",
|
||
"from scipy.io import loadmat\n",
|
||
"\n",
|
||
"# library written for this exercise providing additional functions for assignment submission, and others\n",
|
||
"import utils\n",
|
||
"\n",
|
||
"# define the submission/grader object for this exercise\n",
|
||
"grader = utils.Grader()\n",
|
||
"\n",
|
||
"# tells matplotlib to embed plots within the notebook\n",
|
||
"%matplotlib inline"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Submission and Grading\n",
|
||
"\n",
|
||
"\n",
|
||
"After completing each part of the assignment, be sure to submit your solutions to the grader. The following is a breakdown of how each part of this exercise is scored.\n",
|
||
"\n",
|
||
"\n",
|
||
"| Section | Part | Submission function | Points \n",
|
||
"| :- |:- | :- | :-: \n",
|
||
"| 1 | [Feedforward and Cost Function](#section1) | [`nnCostFunction`](#nnCostFunction) | 30 \n",
|
||
"| 2 | [Regularized Cost Function](#section2) | [`nnCostFunction`](#nnCostFunction) | 15 \n",
|
||
"| 3 | [Sigmoid Gradient](#section3) | [`sigmoidGradient`](#sigmoidGradient) | 5 \n",
|
||
"| 4 | [Neural Net Gradient Function (Backpropagation)](#section4) | [`nnCostFunction`](#nnCostFunction) | 40 \n",
|
||
"| 5 | [Regularized Gradient](#section5) | [`nnCostFunction`](#nnCostFunction) |10 \n",
|
||
"| | Total Points | | 100 \n",
|
||
"\n",
|
||
"\n",
|
||
"You are allowed to submit your solutions multiple times, and we will take only the highest score into consideration.\n",
|
||
"\n",
|
||
"<div class=\"alert alert-block alert-warning\">\n",
|
||
"At the end of each section in this notebook, we have a cell which contains code for submitting the solutions thus far to the grader. Execute the cell to see your score up to the current section. For all your work to be submitted properly, you must execute those cells at least once.\n",
|
||
"</div>"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Neural Networks\n",
|
||
"\n",
|
||
"In the previous exercise, you implemented feedforward propagation for neural networks and used it to predict handwritten digits with the weights we provided. In this exercise, you will implement the backpropagation algorithm to learn the parameters for the neural network.\n",
|
||
"\n",
|
||
"We start the exercise by first loading the dataset. "
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# training data stored in arrays X, y\n",
|
||
"data = loadmat(os.path.join('Data', 'ex4data1.mat'))\n",
|
||
"X, y = data['X'], data['y'].ravel()\n",
|
||
"\n",
|
||
"# set the zero digit to 0, rather than its mapped 10 in this dataset\n",
|
||
"# This is an artifact due to the fact that this dataset was used in \n",
|
||
"# MATLAB where there is no index 0\n",
|
||
"y[y == 10] = 0\n",
|
||
"\n",
|
||
"# Number of training examples\n",
|
||
"m = y.size"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"### 1.1 Visualizing the data\n",
|
||
"\n",
|
||
"You will begin by visualizing a subset of the training set, using the function `displayData`, which is the same function we used in Exercise 3. It is provided in the `utils.py` file for this assignment as well. The dataset is also the same one you used in the previous exercise.\n",
|
||
"\n",
|
||
"There are 5000 training examples in `ex4data1.mat`, where each training example is a 20 pixel by 20 pixel grayscale image of the digit. Each pixel is represented by a floating point number indicating the grayscale intensity at that location. The 20 by 20 grid of pixels is “unrolled” into a 400-dimensional vector. Each\n",
|
||
"of these training examples becomes a single row in our data matrix $X$. This gives us a 5000 by 400 matrix $X$ where every row is a training example for a handwritten digit image.\n",
|
||
"\n",
|
||
"$$ X = \\begin{bmatrix} - \\left(x^{(1)} \\right)^T - \\\\\n",
|
||
"- \\left(x^{(2)} \\right)^T - \\\\\n",
|
||
"\\vdots \\\\\n",
|
||
"- \\left(x^{(m)} \\right)^T - \\\\\n",
|
||
"\\end{bmatrix}\n",
|
||
"$$\n",
|
||
"\n",
|
||
"The second part of the training set is a 5000-dimensional vector `y` that contains labels for the training set. \n",
|
||
"The following cell randomly selects 100 images from the dataset and plots them."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Randomly select 100 data points to display\n",
|
||
"rand_indices = np.random.choice(m, 100, replace=False)\n",
|
||
"sel = X[rand_indices, :]\n",
|
||
"\n",
|
||
"utils.displayData(sel)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"### 1.2 Model representation\n",
|
||
"\n",
|
||
"Our neural network is shown in the following figure.\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"It has 3 layers - an input layer, a hidden layer and an output layer. Recall that our inputs are pixel values\n",
|
||
"of digit images. Since the images are of size $20 \\times 20$, this gives us 400 input layer units (not counting the extra bias unit which always outputs +1). The training data was loaded into the variables `X` and `y` above.\n",
|
||
"\n",
|
||
"You have been provided with a set of network parameters ($\\Theta^{(1)}, \\Theta^{(2)}$) already trained by us. These are stored in `ex4weights.mat` and will be loaded in the next cell of this notebook into `Theta1` and `Theta2`. The parameters have dimensions that are sized for a neural network with 25 units in the second layer and 10 output units (corresponding to the 10 digit classes)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Setup the parameters you will use for this exercise\n",
|
||
"input_layer_size = 400 # 20x20 Input Images of Digits\n",
|
||
"hidden_layer_size = 25 # 25 hidden units\n",
|
||
"num_labels = 10 # 10 labels, from 0 to 9\n",
|
||
"\n",
|
||
"# Load the weights into variables Theta1 and Theta2\n",
|
||
"weights = loadmat(os.path.join('Data', 'ex4weights.mat'))\n",
|
||
"\n",
|
||
"# Theta1 has size 25 x 401\n",
|
||
"# Theta2 has size 10 x 26\n",
|
||
"Theta1, Theta2 = weights['Theta1'], weights['Theta2']\n",
|
||
"\n",
|
||
"# swap first and last columns of Theta2, due to legacy from MATLAB indexing, \n",
|
||
"# since the weight file ex3weights.mat was saved based on MATLAB indexing\n",
|
||
"Theta2 = np.roll(Theta2, 1, axis=0)\n",
|
||
"\n",
|
||
"# Unroll parameters \n",
|
||
"nn_params = np.concatenate([Theta1.ravel(), Theta2.ravel()])"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<a id=\"section1\"></a>\n",
|
||
"### 1.3 Feedforward and cost function\n",
|
||
"\n",
|
||
"Now you will implement the cost function and gradient for the neural network. First, complete the code for the function `nnCostFunction` in the next cell to return the cost.\n",
|
||
"\n",
|
||
"Recall that the cost function for the neural network (without regularization) is:\n",
|
||
"\n",
|
||
"$$ J(\\theta) = \\frac{1}{m} \\sum_{i=1}^{m}\\sum_{k=1}^{K} \\left[ - y_k^{(i)} \\log \\left( \\left( h_\\theta \\left( x^{(i)} \\right) \\right)_k \\right) - \\left( 1 - y_k^{(i)} \\right) \\log \\left( 1 - \\left( h_\\theta \\left( x^{(i)} \\right) \\right)_k \\right) \\right]$$\n",
|
||
"\n",
|
||
"where $h_\\theta \\left( x^{(i)} \\right)$ is computed as shown in the neural network figure above, and K = 10 is the total number of possible labels. Note that $h_\\theta(x^{(i)})_k = a_k^{(3)}$ is the activation (output\n",
|
||
"value) of the $k^{th}$ output unit. Also, recall that whereas the original labels (in the variable y) were 0, 1, ..., 9, for the purpose of training a neural network, we need to encode the labels as vectors containing only values 0 or 1, so that\n",
|
||
"\n",
|
||
"$$ y = \n",
|
||
"\\begin{bmatrix} 1 \\\\ 0 \\\\ 0 \\\\\\vdots \\\\ 0 \\end{bmatrix}, \\quad\n",
|
||
"\\begin{bmatrix} 0 \\\\ 1 \\\\ 0 \\\\ \\vdots \\\\ 0 \\end{bmatrix}, \\quad \\cdots \\quad \\text{or} \\qquad\n",
|
||
"\\begin{bmatrix} 0 \\\\ 0 \\\\ 0 \\\\ \\vdots \\\\ 1 \\end{bmatrix}.\n",
|
||
"$$\n",
|
||
"\n",
|
||
"For example, if $x^{(i)}$ is an image of the digit 5, then the corresponding $y^{(i)}$ (that you should use with the cost function) should be a 10-dimensional vector with $y_5 = 1$, and the other elements equal to 0.\n",
|
||
"\n",
|
||
"You should implement the feedforward computation that computes $h_\\theta(x^{(i)})$ for every example $i$ and sum the cost over all examples. **Your code should also work for a dataset of any size, with any number of labels** (you can assume that there are always at least $K \\ge 3$ labels).\n",
|
||
"\n",
|
||
"<div class=\"alert alert-box alert-warning\">\n",
|
||
"**Implementation Note:** The matrix $X$ contains the examples in rows (i.e., X[i,:] is the i-th training example $x^{(i)}$, expressed as a $n \\times 1$ vector.) When you complete the code in `nnCostFunction`, you will need to add the column of 1’s to the X matrix. The parameters for each unit in the neural network is represented in Theta1 and Theta2 as one row. Specifically, the first row of Theta1 corresponds to the first hidden unit in the second layer. You can use a for-loop over the examples to compute the cost.\n",
|
||
"</div>\n",
|
||
"<a id=\"nnCostFunction\"></a>"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def nnCostFunction(nn_params,\n",
|
||
" input_layer_size,\n",
|
||
" hidden_layer_size,\n",
|
||
" num_labels,\n",
|
||
" X, y, lambda_=0.0):\n",
|
||
" \"\"\"\n",
|
||
" Implements the neural network cost function and gradient for a two layer neural \n",
|
||
" network which performs classification. \n",
|
||
" \n",
|
||
" Parameters\n",
|
||
" ----------\n",
|
||
" nn_params : array_like\n",
|
||
" The parameters for the neural network which are \"unrolled\" into \n",
|
||
" a vector. This needs to be converted back into the weight matrices Theta1\n",
|
||
" and Theta2.\n",
|
||
" \n",
|
||
" input_layer_size : int\n",
|
||
" Number of features for the input layer. \n",
|
||
" \n",
|
||
" hidden_layer_size : int\n",
|
||
" Number of hidden units in the second layer.\n",
|
||
" \n",
|
||
" num_labels : int\n",
|
||
" Total number of labels, or equivalently number of units in output layer. \n",
|
||
" \n",
|
||
" X : array_like\n",
|
||
" Input dataset. A matrix of shape (m x input_layer_size).\n",
|
||
" \n",
|
||
" y : array_like\n",
|
||
" Dataset labels. A vector of shape (m,).\n",
|
||
" \n",
|
||
" lambda_ : float, optional\n",
|
||
" Regularization parameter.\n",
|
||
" \n",
|
||
" Returns\n",
|
||
" -------\n",
|
||
" J : float\n",
|
||
" The computed value for the cost function at the current weight values.\n",
|
||
" \n",
|
||
" grad : array_like\n",
|
||
" An \"unrolled\" vector of the partial derivatives of the concatenatation of\n",
|
||
" neural network weights Theta1 and Theta2.\n",
|
||
" \n",
|
||
" Instructions\n",
|
||
" ------------\n",
|
||
" You should complete the code by working through the following parts.\n",
|
||
" \n",
|
||
" - Part 1: Feedforward the neural network and return the cost in the \n",
|
||
" variable J. After implementing Part 1, you can verify that your\n",
|
||
" cost function computation is correct by verifying the cost\n",
|
||
" computed in the following cell.\n",
|
||
" \n",
|
||
" - Part 2: Implement the backpropagation algorithm to compute the gradients\n",
|
||
" Theta1_grad and Theta2_grad. You should return the partial derivatives of\n",
|
||
" the cost function with respect to Theta1 and Theta2 in Theta1_grad and\n",
|
||
" Theta2_grad, respectively. After implementing Part 2, you can check\n",
|
||
" that your implementation is correct by running checkNNGradients provided\n",
|
||
" in the utils.py module.\n",
|
||
" \n",
|
||
" Note: The vector y passed into the function is a vector of labels\n",
|
||
" containing values from 0..K-1. You need to map this vector into a \n",
|
||
" binary vector of 1's and 0's to be used with the neural network\n",
|
||
" cost function.\n",
|
||
" \n",
|
||
" Hint: We recommend implementing backpropagation using a for-loop\n",
|
||
" over the training examples if you are implementing it for the \n",
|
||
" first time.\n",
|
||
" \n",
|
||
" - Part 3: Implement regularization with the cost function and gradients.\n",
|
||
" \n",
|
||
" Hint: You can implement this around the code for\n",
|
||
" backpropagation. That is, you can compute the gradients for\n",
|
||
" the regularization separately and then add them to Theta1_grad\n",
|
||
" and Theta2_grad from Part 2.\n",
|
||
" \n",
|
||
" Note \n",
|
||
" ----\n",
|
||
" We have provided an implementation for the sigmoid function in the file \n",
|
||
" `utils.py` accompanying this assignment.\n",
|
||
" \"\"\"\n",
|
||
" # Reshape nn_params back into the parameters Theta1 and Theta2, the weight matrices\n",
|
||
" # for our 2 layer neural network\n",
|
||
" Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)],\n",
|
||
" (hidden_layer_size, (input_layer_size + 1)))\n",
|
||
"\n",
|
||
" Theta2 = np.reshape(nn_params[(hidden_layer_size * (input_layer_size + 1)):],\n",
|
||
" (num_labels, (hidden_layer_size + 1)))\n",
|
||
"\n",
|
||
" # Setup some useful variables\n",
|
||
" m = y.size\n",
|
||
" \n",
|
||
" # You need to return the following variables correctly \n",
|
||
" J = 0\n",
|
||
" Theta1_grad = np.zeros(Theta1.shape)\n",
|
||
" Theta2_grad = np.zeros(Theta2.shape)\n",
|
||
"\n",
|
||
" # ====================== YOUR CODE HERE ======================\n",
|
||
"\n",
|
||
" \n",
|
||
" \n",
|
||
" # ================================================================\n",
|
||
" # Unroll gradients\n",
|
||
" # grad = np.concatenate([Theta1_grad.ravel(order=order), Theta2_grad.ravel(order=order)])\n",
|
||
" grad = np.concatenate([Theta1_grad.ravel(), Theta2_grad.ravel()])\n",
|
||
"\n",
|
||
" return J, grad"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<div class=\"alert alert-box alert-warning\">\n",
|
||
"Use the following links to go back to the different parts of this exercise that require to modify the function `nnCostFunction`.<br>\n",
|
||
"\n",
|
||
"Back to:\n",
|
||
"- [Feedforward and cost function](#section1)\n",
|
||
"- [Regularized cost](#section2)\n",
|
||
"- [Neural Network Gradient (Backpropagation)](#section4)\n",
|
||
"- [Regularized Gradient](#section5)\n",
|
||
"</div>"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"Once you are done, call your `nnCostFunction` using the loaded set of parameters for `Theta1` and `Theta2`. You should see that the cost is about 0.287629."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"lambda_ = 0\n",
|
||
"J, _ = nnCostFunction(nn_params, input_layer_size, hidden_layer_size,\n",
|
||
" num_labels, X, y, lambda_)\n",
|
||
"print('Cost at parameters (loaded from ex4weights): %.6f ' % J)\n",
|
||
"print('The cost should be about : 0.287629.')"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"*You should now submit your solutions.*"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"grader = utils.Grader()\n",
|
||
"grader[1] = nnCostFunction\n",
|
||
"grader.grade()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<a id=\"section2\"></a>\n",
|
||
"### 1.4 Regularized cost function\n",
|
||
"\n",
|
||
"The cost function for neural networks with regularization is given by:\n",
|
||
"\n",
|
||
"\n",
|
||
"$$ J(\\theta) = \\frac{1}{m} \\sum_{i=1}^{m}\\sum_{k=1}^{K} \\left[ - y_k^{(i)} \\log \\left( \\left( h_\\theta \\left( x^{(i)} \\right) \\right)_k \\right) - \\left( 1 - y_k^{(i)} \\right) \\log \\left( 1 - \\left( h_\\theta \\left( x^{(i)} \\right) \\right)_k \\right) \\right] + \\frac{\\lambda}{2 m} \\left[ \\sum_{j=1}^{25} \\sum_{k=1}^{400} \\left( \\Theta_{j,k}^{(1)} \\right)^2 + \\sum_{j=1}^{10} \\sum_{k=1}^{25} \\left( \\Theta_{j,k}^{(2)} \\right)^2 \\right] $$\n",
|
||
"\n",
|
||
"You can assume that the neural network will only have 3 layers - an input layer, a hidden layer and an output layer. However, your code should work for any number of input units, hidden units and outputs units. While we\n",
|
||
"have explicitly listed the indices above for $\\Theta^{(1)}$ and $\\Theta^{(2)}$ for clarity, do note that your code should in general work with $\\Theta^{(1)}$ and $\\Theta^{(2)}$ of any size. Note that you should not be regularizing the terms that correspond to the bias. For the matrices `Theta1` and `Theta2`, this corresponds to the first column of each matrix. You should now add regularization to your cost function. Notice that you can first compute the unregularized cost function $J$ using your existing `nnCostFunction` and then later add the cost for the regularization terms.\n",
|
||
"\n",
|
||
"[Click here to go back to `nnCostFunction` for editing.](#nnCostFunction)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"Once you are done, the next cell will call your `nnCostFunction` using the loaded set of parameters for `Theta1` and `Theta2`, and $\\lambda = 1$. You should see that the cost is about 0.383770."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Weight regularization parameter (we set this to 1 here).\n",
|
||
"lambda_ = 1\n",
|
||
"J, _ = nnCostFunction(nn_params, input_layer_size, hidden_layer_size,\n",
|
||
" num_labels, X, y, lambda_)\n",
|
||
"\n",
|
||
"print('Cost at parameters (loaded from ex4weights): %.6f' % J)\n",
|
||
"print('This value should be about : 0.383770.')"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"*You should now submit your solutions.*"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"grader[2] = nnCostFunction\n",
|
||
"grader.grade()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## 2 Backpropagation\n",
|
||
"\n",
|
||
"In this part of the exercise, you will implement the backpropagation algorithm to compute the gradient for the neural network cost function. You will need to update the function `nnCostFunction` so that it returns an appropriate value for `grad`. Once you have computed the gradient, you will be able to train the neural network by minimizing the cost function $J(\\theta)$ using an advanced optimizer such as `scipy`'s `optimize.minimize`.\n",
|
||
"You will first implement the backpropagation algorithm to compute the gradients for the parameters for the (unregularized) neural network. After you have verified that your gradient computation for the unregularized case is correct, you will implement the gradient for the regularized neural network."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<a id=\"section3\"></a>\n",
|
||
"### 2.1 Sigmoid Gradient\n",
|
||
"\n",
|
||
"To help you get started with this part of the exercise, you will first implement\n",
|
||
"the sigmoid gradient function. The gradient for the sigmoid function can be\n",
|
||
"computed as\n",
|
||
"\n",
|
||
"$$ g'(z) = \\frac{d}{dz} g(z) = g(z)\\left(1-g(z)\\right) $$\n",
|
||
"\n",
|
||
"where\n",
|
||
"\n",
|
||
"$$ \\text{sigmoid}(z) = g(z) = \\frac{1}{1 + e^{-z}} $$\n",
|
||
"\n",
|
||
"Now complete the implementation of `sigmoidGradient` in the next cell.\n",
|
||
"<a id=\"sigmoidGradient\"></a>"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def sigmoidGradient(z):\n",
|
||
" \"\"\"\n",
|
||
" Computes the gradient of the sigmoid function evaluated at z. \n",
|
||
" This should work regardless if z is a matrix or a vector. \n",
|
||
" In particular, if z is a vector or matrix, you should return\n",
|
||
" the gradient for each element.\n",
|
||
" \n",
|
||
" Parameters\n",
|
||
" ----------\n",
|
||
" z : array_like\n",
|
||
" A vector or matrix as input to the sigmoid function. \n",
|
||
" \n",
|
||
" Returns\n",
|
||
" --------\n",
|
||
" g : array_like\n",
|
||
" Gradient of the sigmoid function. Has the same shape as z. \n",
|
||
" \n",
|
||
" Instructions\n",
|
||
" ------------\n",
|
||
" Compute the gradient of the sigmoid function evaluated at\n",
|
||
" each value of z (z can be a matrix, vector or scalar).\n",
|
||
" \n",
|
||
" Note\n",
|
||
" ----\n",
|
||
" We have provided an implementation of the sigmoid function \n",
|
||
" in `utils.py` file accompanying this assignment.\n",
|
||
" \"\"\"\n",
|
||
"\n",
|
||
" g = np.zeros(z.shape)\n",
|
||
"\n",
|
||
" # ====================== YOUR CODE HERE ======================\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
" # =============================================================\n",
|
||
" return g"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"When you are done, the following cell call `sigmoidGradient` on a given vector `z`. Try testing a few values by calling `sigmoidGradient(z)`. For large values (both positive and negative) of z, the gradient should be close to 0. When $z = 0$, the gradient should be exactly 0.25. Your code should also work with vectors and matrices. For a matrix, your function should perform the sigmoid gradient function on every element."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"z = np.array([-1, -0.5, 0, 0.5, 1])\n",
|
||
"g = sigmoidGradient(z)\n",
|
||
"print('Sigmoid gradient evaluated at [-1 -0.5 0 0.5 1]:\\n ')\n",
|
||
"print(g)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"*You should now submit your solutions.*"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"grader[3] = sigmoidGradient\n",
|
||
"grader.grade()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## 2.2 Random Initialization\n",
|
||
"\n",
|
||
"When training neural networks, it is important to randomly initialize the parameters for symmetry breaking. One effective strategy for random initialization is to randomly select values for $\\Theta^{(l)}$ uniformly in the range $[-\\epsilon_{init}, \\epsilon_{init}]$. You should use $\\epsilon_{init} = 0.12$. This range of values ensures that the parameters are kept small and makes the learning more efficient.\n",
|
||
"\n",
|
||
"<div class=\"alert alert-box alert-warning\">\n",
|
||
"One effective strategy for choosing $\\epsilon_{init}$ is to base it on the number of units in the network. A good choice of $\\epsilon_{init}$ is $\\epsilon_{init} = \\frac{\\sqrt{6}}{\\sqrt{L_{in} + L_{out}}}$ where $L_{in} = s_l$ and $L_{out} = s_{l+1}$ are the number of units in the layers adjacent to $\\Theta^{l}$.\n",
|
||
"</div>\n",
|
||
"\n",
|
||
"Your job is to complete the function `randInitializeWeights` to initialize the weights for $\\Theta$. Modify the function by filling in the following code:\n",
|
||
"\n",
|
||
"```python\n",
|
||
"# Randomly initialize the weights to small values\n",
|
||
"W = np.random.rand(L_out, 1 + L_in) * 2 * epsilon_init - epsilon_init\n",
|
||
"```\n",
|
||
"Note that we give the function an argument for $\\epsilon$ with default value `epsilon_init = 0.12`."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def randInitializeWeights(L_in, L_out, epsilon_init=0.12):\n",
|
||
" \"\"\"\n",
|
||
" Randomly initialize the weights of a layer in a neural network.\n",
|
||
" \n",
|
||
" Parameters\n",
|
||
" ----------\n",
|
||
" L_in : int\n",
|
||
" Number of incomming connections.\n",
|
||
" \n",
|
||
" L_out : int\n",
|
||
" Number of outgoing connections. \n",
|
||
" \n",
|
||
" epsilon_init : float, optional\n",
|
||
" Range of values which the weight can take from a uniform \n",
|
||
" distribution.\n",
|
||
" \n",
|
||
" Returns\n",
|
||
" -------\n",
|
||
" W : array_like\n",
|
||
" The weight initialiatized to random values. Note that W should\n",
|
||
" be set to a matrix of size(L_out, 1 + L_in) as\n",
|
||
" the first column of W handles the \"bias\" terms.\n",
|
||
" \n",
|
||
" Instructions\n",
|
||
" ------------\n",
|
||
" Initialize W randomly so that we break the symmetry while training\n",
|
||
" the neural network. Note that the first column of W corresponds \n",
|
||
" to the parameters for the bias unit.\n",
|
||
" \"\"\"\n",
|
||
"\n",
|
||
" # You need to return the following variables correctly \n",
|
||
" W = np.zeros((L_out, 1 + L_in))\n",
|
||
"\n",
|
||
" # ====================== YOUR CODE HERE ======================\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
" # ============================================================\n",
|
||
" return W"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"*You do not need to submit any code for this part of the exercise.*\n",
|
||
"\n",
|
||
"Execute the following cell to initialize the weights for the 2 layers in the neural network using the `randInitializeWeights` function."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"print('Initializing Neural Network Parameters ...')\n",
|
||
"\n",
|
||
"initial_Theta1 = randInitializeWeights(input_layer_size, hidden_layer_size)\n",
|
||
"initial_Theta2 = randInitializeWeights(hidden_layer_size, num_labels)\n",
|
||
"\n",
|
||
"# Unroll parameters\n",
|
||
"initial_nn_params = np.concatenate([initial_Theta1.ravel(), initial_Theta2.ravel()], axis=0)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<a id=\"section4\"></a>\n",
|
||
"### 2.4 Backpropagation\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"Now, you will implement the backpropagation algorithm. Recall that the intuition behind the backpropagation algorithm is as follows. Given a training example $(x^{(t)}, y^{(t)})$, we will first run a “forward pass” to compute all the activations throughout the network, including the output value of the hypothesis $h_\\theta(x)$. Then, for each node $j$ in layer $l$, we would like to compute an “error term” $\\delta_j^{(l)}$ that measures how much that node was “responsible” for any errors in our output.\n",
|
||
"\n",
|
||
"For an output node, we can directly measure the difference between the network’s activation and the true target value, and use that to define $\\delta_j^{(3)}$ (since layer 3 is the output layer). For the hidden units, you will compute $\\delta_j^{(l)}$ based on a weighted average of the error terms of the nodes in layer $(l+1)$. In detail, here is the backpropagation algorithm (also depicted in the figure above). You should implement steps 1 to 4 in a loop that processes one example at a time. Concretely, you should implement a for-loop `for t in range(m)` and place steps 1-4 below inside the for-loop, with the $t^{th}$ iteration performing the calculation on the $t^{th}$ training example $(x^{(t)}, y^{(t)})$. Step 5 will divide the accumulated gradients by $m$ to obtain the gradients for the neural network cost function.\n",
|
||
"\n",
|
||
"1. Set the input layer’s values $(a^{(1)})$ to the $t^{th }$training example $x^{(t)}$. Perform a feedforward pass, computing the activations $(z^{(2)}, a^{(2)}, z^{(3)}, a^{(3)})$ for layers 2 and 3. Note that you need to add a `+1` term to ensure that the vectors of activations for layers $a^{(1)}$ and $a^{(2)}$ also include the bias unit. In `numpy`, if a 1 is a column matrix, adding one corresponds to `a_1 = np.concatenate([np.ones((m, 1)), a_1], axis=1)`.\n",
|
||
"\n",
|
||
"1. For each output unit $k$ in layer 3 (the output layer), set \n",
|
||
"$$\\delta_k^{(3)} = \\left(a_k^{(3)} - y_k \\right)$$\n",
|
||
"where $y_k \\in \\{0, 1\\}$ indicates whether the current training example belongs to class $k$ $(y_k = 1)$, or if it belongs to a different class $(y_k = 0)$. You may find logical arrays helpful for this task (explained in the previous programming exercise).\n",
|
||
"\n",
|
||
"1. For the hidden layer $l = 2$, set \n",
|
||
"$$ \\delta^{(2)} = \\left( \\Theta^{(2)} \\right)^T \\delta^{(3)} * g'\\left(z^{(2)} \\right)$$\n",
|
||
"Note that the symbol $*$ performs element wise multiplication in `numpy`.\n",
|
||
"\n",
|
||
"1. Accumulate the gradient from this example using the following formula. Note that you should skip or remove $\\delta_0^{(2)}$. In `numpy`, removing $\\delta_0^{(2)}$ corresponds to `delta_2 = delta_2[1:]`.\n",
|
||
"$$ \\Delta^{(l)} = \\Delta^{(l)} + \\delta^{(l+1)} (a^{(l)})^{(T)} $$\n",
|
||
"\n",
|
||
"1. Obtain the (unregularized) gradient for the neural network cost function by dividing the accumulated gradients by $\\frac{1}{m}$:\n",
|
||
"$$ \\frac{\\partial}{\\partial \\Theta_{ij}^{(l)}} J(\\Theta) = D_{ij}^{(l)} = \\frac{1}{m} \\Delta_{ij}^{(l)}$$\n",
|
||
"\n",
|
||
"<div class=\"alert alert-box alert-warning\">\n",
|
||
"**Python/Numpy tip**: You should implement the backpropagation algorithm only after you have successfully completed the feedforward and cost functions. While implementing the backpropagation alogrithm, it is often useful to use the `shape` function to print out the shapes of the variables you are working with if you run into dimension mismatch errors.\n",
|
||
"</div>\n",
|
||
"\n",
|
||
"[Click here to go back and update the function `nnCostFunction` with the backpropagation algorithm](#nnCostFunction).\n",
|
||
"\n",
|
||
"\n",
|
||
"**Note:** If the iterative solution provided above is proving to be difficult to implement, try implementing the vectorized approach which is easier to implement in the opinion of the moderators of this course. You can find the tutorial for the vectorized approach [here](https://www.coursera.org/learn/machine-learning/discussions/all/threads/a8Kce_WxEeS16yIACyoj1Q)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"After you have implemented the backpropagation algorithm, we will proceed to run gradient checking on your implementation. The gradient check will allow you to increase your confidence that your code is\n",
|
||
"computing the gradients correctly.\n",
|
||
"\n",
|
||
"### 2.4 Gradient checking \n",
|
||
"\n",
|
||
"In your neural network, you are minimizing the cost function $J(\\Theta)$. To perform gradient checking on your parameters, you can imagine “unrolling” the parameters $\\Theta^{(1)}$, $\\Theta^{(2)}$ into a long vector $\\theta$. By doing so, you can think of the cost function being $J(\\Theta)$ instead and use the following gradient checking procedure.\n",
|
||
"\n",
|
||
"Suppose you have a function $f_i(\\theta)$ that purportedly computes $\\frac{\\partial}{\\partial \\theta_i} J(\\theta)$; you’d like to check if $f_i$ is outputting correct derivative values.\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\text{Let } \\theta^{(i+)} = \\theta + \\begin{bmatrix} 0 \\\\ 0 \\\\ \\vdots \\\\ \\epsilon \\\\ \\vdots \\\\ 0 \\end{bmatrix}\n",
|
||
"\\quad \\text{and} \\quad \\theta^{(i-)} = \\theta - \\begin{bmatrix} 0 \\\\ 0 \\\\ \\vdots \\\\ \\epsilon \\\\ \\vdots \\\\ 0 \\end{bmatrix}\n",
|
||
"$$\n",
|
||
"\n",
|
||
"So, $\\theta^{(i+)}$ is the same as $\\theta$, except its $i^{th}$ element has been incremented by $\\epsilon$. Similarly, $\\theta^{(i−)}$ is the corresponding vector with the $i^{th}$ element decreased by $\\epsilon$. You can now numerically verify $f_i(\\theta)$’s correctness by checking, for each $i$, that:\n",
|
||
"\n",
|
||
"$$ f_i\\left( \\theta \\right) \\approx \\frac{J\\left( \\theta^{(i+)}\\right) - J\\left( \\theta^{(i-)} \\right)}{2\\epsilon} $$\n",
|
||
"\n",
|
||
"The degree to which these two values should approximate each other will depend on the details of $J$. But assuming $\\epsilon = 10^{-4}$, you’ll usually find that the left- and right-hand sides of the above will agree to at least 4 significant digits (and often many more).\n",
|
||
"\n",
|
||
"We have implemented the function to compute the numerical gradient for you in `computeNumericalGradient` (within the file `utils.py`). While you are not required to modify the file, we highly encourage you to take a look at the code to understand how it works.\n",
|
||
"\n",
|
||
"In the next cell we will run the provided function `checkNNGradients` which will create a small neural network and dataset that will be used for checking your gradients. If your backpropagation implementation is correct,\n",
|
||
"you should see a relative difference that is less than 1e-9.\n",
|
||
"\n",
|
||
"<div class=\"alert alert-box alert-success\">\n",
|
||
"**Practical Tip**: When performing gradient checking, it is much more efficient to use a small neural network with a relatively small number of input units and hidden units, thus having a relatively small number\n",
|
||
"of parameters. Each dimension of $\\theta$ requires two evaluations of the cost function and this can be expensive. In the function `checkNNGradients`, our code creates a small random model and dataset which is used with `computeNumericalGradient` for gradient checking. Furthermore, after you are confident that your gradient computations are correct, you should turn off gradient checking before running your learning algorithm.\n",
|
||
"</div>\n",
|
||
"\n",
|
||
"<div class=\"alert alert-box alert-success\">\n",
|
||
" <b>Practical Tip:</b> Gradient checking works for any function where you are computing the cost and the gradient. Concretely, you can use the same `computeNumericalGradient` function to check if your gradient implementations for the other exercises are correct too (e.g., logistic regression’s cost function).\n",
|
||
"</div>"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 1,
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"ename": "NameError",
|
||
"evalue": "name 'utils' is not defined",
|
||
"output_type": "error",
|
||
"traceback": [
|
||
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
||
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
|
||
"\u001b[0;32m<ipython-input-1-d4995b4088e4>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mutils\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcheckNNGradients\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnnCostFunction\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
|
||
"\u001b[0;31mNameError\u001b[0m: name 'utils' is not defined"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"utils.checkNNGradients(nnCostFunction)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"*Once your cost function passes the gradient check for the (unregularized) neural network cost function, you should submit the neural network gradient function (backpropagation).*"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"grader[4] = nnCostFunction\n",
|
||
"grader.grade()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"<a id=\"section5\"></a>\n",
|
||
"### 2.5 Regularized Neural Network\n",
|
||
"\n",
|
||
"After you have successfully implemented the backpropagation algorithm, you will add regularization to the gradient. To account for regularization, it turns out that you can add this as an additional term *after* computing the gradients using backpropagation.\n",
|
||
"\n",
|
||
"Specifically, after you have computed $\\Delta_{ij}^{(l)}$ using backpropagation, you should add regularization using\n",
|
||
"\n",
|
||
"$$ \\begin{align} \n",
|
||
"& \\frac{\\partial}{\\partial \\Theta_{ij}^{(l)}} J(\\Theta) = D_{ij}^{(l)} = \\frac{1}{m} \\Delta_{ij}^{(l)} & \\qquad \\text{for } j = 0 \\\\\n",
|
||
"& \\frac{\\partial}{\\partial \\Theta_{ij}^{(l)}} J(\\Theta) = D_{ij}^{(l)} = \\frac{1}{m} \\Delta_{ij}^{(l)} + \\frac{\\lambda}{m} \\Theta_{ij}^{(l)} & \\qquad \\text{for } j \\ge 1\n",
|
||
"\\end{align}\n",
|
||
"$$\n",
|
||
"\n",
|
||
"Note that you should *not* be regularizing the first column of $\\Theta^{(l)}$ which is used for the bias term. Furthermore, in the parameters $\\Theta_{ij}^{(l)}$, $i$ is indexed starting from 1, and $j$ is indexed starting from 0. Thus, \n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\Theta^{(l)} = \\begin{bmatrix}\n",
|
||
"\\Theta_{1,0}^{(i)} & \\Theta_{1,1}^{(l)} & \\cdots \\\\\n",
|
||
"\\Theta_{2,0}^{(i)} & \\Theta_{2,1}^{(l)} & \\cdots \\\\\n",
|
||
"\\vdots & ~ & \\ddots\n",
|
||
"\\end{bmatrix}\n",
|
||
"$$\n",
|
||
"\n",
|
||
"[Now modify your code that computes grad in `nnCostFunction` to account for regularization.](#nnCostFunction)\n",
|
||
"\n",
|
||
"After you are done, the following cell runs gradient checking on your implementation. If your code is correct, you should expect to see a relative difference that is less than 1e-9."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Check gradients by running checkNNGradients\n",
|
||
"lambda_ = 3\n",
|
||
"utils.checkNNGradients(nnCostFunction, lambda_)\n",
|
||
"\n",
|
||
"# Also output the costFunction debugging values\n",
|
||
"debug_J, _ = nnCostFunction(nn_params, input_layer_size,\n",
|
||
" hidden_layer_size, num_labels, X, y, lambda_)\n",
|
||
"\n",
|
||
"print('\\n\\nCost at (fixed) debugging parameters (w/ lambda = %f): %f ' % (lambda_, debug_J))\n",
|
||
"print('(for lambda = 3, this value should be about 0.576051)')"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"grader[5] = nnCostFunction\n",
|
||
"grader.grade()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"### 2.6 Learning parameters using `scipy.optimize.minimize`\n",
|
||
"\n",
|
||
"After you have successfully implemented the neural network cost function\n",
|
||
"and gradient computation, the next step we will use `scipy`'s minimization to learn a good set parameters."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# After you have completed the assignment, change the maxiter to a larger\n",
|
||
"# value to see how more training helps.\n",
|
||
"options= {'maxiter': 100}\n",
|
||
"\n",
|
||
"# You should also try different values of lambda\n",
|
||
"lambda_ = 1\n",
|
||
"\n",
|
||
"# Create \"short hand\" for the cost function to be minimized\n",
|
||
"costFunction = lambda p: nnCostFunction(p, input_layer_size,\n",
|
||
" hidden_layer_size,\n",
|
||
" num_labels, X, y, lambda_)\n",
|
||
"\n",
|
||
"# Now, costFunction is a function that takes in only one argument\n",
|
||
"# (the neural network parameters)\n",
|
||
"res = optimize.minimize(costFunction,\n",
|
||
" initial_nn_params,\n",
|
||
" jac=True,\n",
|
||
" method='TNC',\n",
|
||
" options=options)\n",
|
||
"\n",
|
||
"# get the solution of the optimization\n",
|
||
"nn_params = res.x\n",
|
||
" \n",
|
||
"# Obtain Theta1 and Theta2 back from nn_params\n",
|
||
"Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)],\n",
|
||
" (hidden_layer_size, (input_layer_size + 1)))\n",
|
||
"\n",
|
||
"Theta2 = np.reshape(nn_params[(hidden_layer_size * (input_layer_size + 1)):],\n",
|
||
" (num_labels, (hidden_layer_size + 1)))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"After the training completes, we will proceed to report the training accuracy of your classifier by computing the percentage of examples it got correct. If your implementation is correct, you should see a reported\n",
|
||
"training accuracy of about 95.3% (this may vary by about 1% due to the random initialization). It is possible to get higher training accuracies by training the neural network for more iterations. We encourage you to try\n",
|
||
"training the neural network for more iterations (e.g., set `maxiter` to 400) and also vary the regularization parameter $\\lambda$. With the right learning settings, it is possible to get the neural network to perfectly fit the training set."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"pred = utils.predict(Theta1, Theta2, X)\n",
|
||
"print('Training Set Accuracy: %f' % (np.mean(pred == y) * 100))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## 3 Visualizing the Hidden Layer\n",
|
||
"\n",
|
||
"One way to understand what your neural network is learning is to visualize what the representations captured by the hidden units. Informally, given a particular hidden unit, one way to visualize what it computes is to find an input $x$ that will cause it to activate (that is, to have an activation value \n",
|
||
"($a_i^{(l)}$) close to 1). For the neural network you trained, notice that the $i^{th}$ row of $\\Theta^{(1)}$ is a 401-dimensional vector that represents the parameter for the $i^{th}$ hidden unit. If we discard the bias term, we get a 400 dimensional vector that represents the weights from each input pixel to the hidden unit.\n",
|
||
"\n",
|
||
"Thus, one way to visualize the “representation” captured by the hidden unit is to reshape this 400 dimensional vector into a 20 × 20 image and display it (It turns out that this is equivalent to finding the input that gives the highest activation for the hidden unit, given a “norm” constraint on the input (i.e., $||x||_2 \\le 1$)). \n",
|
||
"\n",
|
||
"The next cell does this by using the `displayData` function and it will show you an image with 25 units,\n",
|
||
"each corresponding to one hidden unit in the network. In your trained network, you should find that the hidden units corresponds roughly to detectors that look for strokes and other patterns in the input."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"utils.displayData(Theta1[:, 1:])"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"### 3.1 Optional (ungraded) exercise\n",
|
||
"\n",
|
||
"In this part of the exercise, you will get to try out different learning settings for the neural network to see how the performance of the neural network varies with the regularization parameter $\\lambda$ and number of training steps (the `maxiter` option when using `scipy.optimize.minimize`). Neural networks are very powerful models that can form highly complex decision boundaries. Without regularization, it is possible for a neural network to “overfit” a training set so that it obtains close to 100% accuracy on the training set but does not as well on new examples that it has not seen before. You can set the regularization $\\lambda$ to a smaller value and the `maxiter` parameter to a higher number of iterations to see this for youself."
|
||
]
|
||
}
|
||
],
|
||
"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.6"
|
||
}
|
||
},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 2
|
||
}
|