{ "cells": [ { "cell_type": "markdown", "metadata": { "tags": [ "pdf-title" ] }, "source": [ "# Implementing a Neural Network\n", "In this exercise we will develop a neural network with fully-connected layers to perform classification, and test it out on the CIFAR-10 dataset." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "pdf-ignore" ] }, "outputs": [], "source": [ "# A bit of setup\n", "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "from cs231n.classifiers.neural_net import TwoLayerNet\n", "\n", "%matplotlib inline\n", "plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\n", "plt.rcParams['image.interpolation'] = 'nearest'\n", "plt.rcParams['image.cmap'] = 'gray'\n", "\n", "# for auto-reloading external modules\n", "# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n", "%load_ext autoreload\n", "%autoreload 2\n", "\n", "def rel_error(x, y):\n", " \"\"\" returns relative error \"\"\"\n", " return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "pdf-ignore" ] }, "source": [ "We will use the class `TwoLayerNet` in the file `cs231n/classifiers/neural_net.py` to represent instances of our network. The network parameters are stored in the instance variable `self.params` where keys are string parameter names and values are numpy arrays. Below, we initialize toy data and a toy model that we will use to develop your implementation." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "pdf-ignore" ] }, "outputs": [], "source": [ "# Create a small net and some toy data to check your implementations.\n", "# Note that we set the random seed for repeatable experiments.\n", "\n", "input_size = 4\n", "hidden_size = 10\n", "num_classes = 3\n", "num_inputs = 5\n", "\n", "def init_toy_model():\n", " np.random.seed(0)\n", " return TwoLayerNet(input_size, hidden_size, num_classes, std=1e-1)\n", "\n", "def init_toy_data():\n", " np.random.seed(1)\n", " X = 10 * np.random.randn(num_inputs, input_size)\n", " y = np.array([0, 1, 2, 2, 1])\n", " return X, y\n", "\n", "net = init_toy_model()\n", "X, y = init_toy_data()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Forward pass: compute scores\n", "Open the file `cs231n/classifiers/neural_net.py` and look at the method `TwoLayerNet.loss`. This function is very similar to the loss functions you have written for the SVM and Softmax exercises: It takes the data and weights and computes the class scores, the loss, and the gradients on the parameters. \n", "\n", "Implement the first part of the forward pass which uses the weights and biases to compute the scores for all inputs." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scores = net.loss(X)\n", "print('Your scores:')\n", "print(scores)\n", "print()\n", "print('correct scores:')\n", "correct_scores = np.asarray([\n", " [-0.81233741, -1.27654624, -0.70335995],\n", " [-0.17129677, -1.18803311, -0.47310444],\n", " [-0.51590475, -1.01354314, -0.8504215 ],\n", " [-0.15419291, -0.48629638, -0.52901952],\n", " [-0.00618733, -0.12435261, -0.15226949]])\n", "print(correct_scores)\n", "print()\n", "\n", "# The difference should be very small. We get < 1e-7\n", "print('Difference between your scores and correct scores:')\n", "print(np.sum(np.abs(scores - correct_scores)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Forward pass: compute loss\n", "In the same function, implement the second part that computes the data and regularization loss." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "loss, _ = net.loss(X, y, reg=0.05)\n", "correct_loss = 1.30378789133\n", "\n", "# should be very small, we get < 1e-12\n", "print('Difference between your loss and correct loss:')\n", "print(np.sum(np.abs(loss - correct_loss)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Backward pass\n", "Implement the rest of the function. This will compute the gradient of the loss with respect to the variables `W1`, `b1`, `W2`, and `b2`. Now that you (hopefully!) have a correctly implemented forward pass, you can debug your backward pass using a numeric gradient check:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from cs231n.gradient_check import eval_numerical_gradient\n", "\n", "# Use numeric gradient checking to check your implementation of the backward pass.\n", "# If your implementation is correct, the difference between the numeric and\n", "# analytic gradients should be less than 1e-8 for each of W1, W2, b1, and b2.\n", "\n", "loss, grads = net.loss(X, y, reg=0.05)\n", "\n", "# these should all be less than 1e-8 or so\n", "for param_name in grads:\n", " f = lambda W: net.loss(X, y, reg=0.05)[0]\n", " param_grad_num = eval_numerical_gradient(f, net.params[param_name], verbose=False)\n", " print('%s max relative error: %e' % (param_name, rel_error(param_grad_num, grads[param_name])))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Train the network\n", "To train the network we will use stochastic gradient descent (SGD), similar to the SVM and Softmax classifiers. Look at the function `TwoLayerNet.train` and fill in the missing sections to implement the training procedure. This should be very similar to the training procedure you used for the SVM and Softmax classifiers. You will also have to implement `TwoLayerNet.predict`, as the training process periodically performs prediction to keep track of accuracy over time while the network trains.\n", "\n", "Once you have implemented the method, run the code below to train a two-layer network on toy data. You should achieve a training loss less than 0.02." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "net = init_toy_model()\n", "stats = net.train(X, y, X, y,\n", " learning_rate=1e-1, reg=5e-6,\n", " num_iters=100, verbose=False)\n", "\n", "print('Final training loss: ', stats['loss_history'][-1])\n", "\n", "# plot the loss history\n", "plt.plot(stats['loss_history'])\n", "plt.xlabel('iteration')\n", "plt.ylabel('training loss')\n", "plt.title('Training Loss history')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Load the data\n", "Now that you have implemented a two-layer network that passes gradient checks and works on toy data, it's time to load up our favorite CIFAR-10 data so we can use it to train a classifier on a real dataset." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "pdf-ignore" ] }, "outputs": [], "source": [ "from cs231n.data_utils import load_CIFAR10\n", "\n", "def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000):\n", " \"\"\"\n", " Load the CIFAR-10 dataset from disk and perform preprocessing to prepare\n", " it for the two-layer neural net classifier. These are the same steps as\n", " we used for the SVM, but condensed to a single function. \n", " \"\"\"\n", " # Load the raw CIFAR-10 data\n", " cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'\n", " \n", " # Cleaning up variables to prevent loading data multiple times (which may cause memory issue)\n", " try:\n", " del X_train, y_train\n", " del X_test, y_test\n", " print('Clear previously loaded data.')\n", " except:\n", " pass\n", "\n", " X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)\n", " \n", " # Subsample the data\n", " mask = list(range(num_training, num_training + num_validation))\n", " X_val = X_train[mask]\n", " y_val = y_train[mask]\n", " mask = list(range(num_training))\n", " X_train = X_train[mask]\n", " y_train = y_train[mask]\n", " mask = list(range(num_test))\n", " X_test = X_test[mask]\n", " y_test = y_test[mask]\n", "\n", " # Normalize the data: subtract the mean image\n", " mean_image = np.mean(X_train, axis=0)\n", " X_train -= mean_image\n", " X_val -= mean_image\n", " X_test -= mean_image\n", "\n", " # Reshape data to rows\n", " X_train = X_train.reshape(num_training, -1)\n", " X_val = X_val.reshape(num_validation, -1)\n", " X_test = X_test.reshape(num_test, -1)\n", "\n", " return X_train, y_train, X_val, y_val, X_test, y_test\n", "\n", "\n", "# Invoke the above function to get our data.\n", "X_train, y_train, X_val, y_val, X_test, y_test = get_CIFAR10_data()\n", "print('Train data shape: ', X_train.shape)\n", "print('Train labels shape: ', y_train.shape)\n", "print('Validation data shape: ', X_val.shape)\n", "print('Validation labels shape: ', y_val.shape)\n", "print('Test data shape: ', X_test.shape)\n", "print('Test labels shape: ', y_test.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Train a network\n", "To train our network we will use SGD. In addition, we will adjust the learning rate with an exponential learning rate schedule as optimization proceeds; after each epoch, we will reduce the learning rate by multiplying it by a decay rate." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "code" ] }, "outputs": [], "source": [ "input_size = 32 * 32 * 3\n", "hidden_size = 50\n", "num_classes = 10\n", "net = TwoLayerNet(input_size, hidden_size, num_classes)\n", "\n", "# Train the network\n", "stats = net.train(X_train, y_train, X_val, y_val,\n", " num_iters=1000, batch_size=200,\n", " learning_rate=1e-4, learning_rate_decay=0.95,\n", " reg=0.25, verbose=True)\n", "\n", "# Predict on the validation set\n", "val_acc = (net.predict(X_val) == y_val).mean()\n", "print('Validation accuracy: ', val_acc)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Debug the training\n", "With the default parameters we provided above, you should get a validation accuracy of about 0.29 on the validation set. This isn't very good.\n", "\n", "One strategy for getting insight into what's wrong is to plot the loss function and the accuracies on the training and validation sets during optimization.\n", "\n", "Another strategy is to visualize the weights that were learned in the first layer of the network. In most neural networks trained on visual data, the first layer weights typically show some visible structure when visualized." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot the loss function and train / validation accuracies\n", "plt.subplot(2, 1, 1)\n", "plt.plot(stats['loss_history'])\n", "plt.title('Loss history')\n", "plt.xlabel('Iteration')\n", "plt.ylabel('Loss')\n", "\n", "plt.subplot(2, 1, 2)\n", "plt.plot(stats['train_acc_history'], label='train')\n", "plt.plot(stats['val_acc_history'], label='val')\n", "plt.title('Classification accuracy history')\n", "plt.xlabel('Epoch')\n", "plt.ylabel('Classification accuracy')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from cs231n.vis_utils import visualize_grid\n", "\n", "# Visualize the weights of the network\n", "\n", "def show_net_weights(net):\n", " W1 = net.params['W1']\n", " W1 = W1.reshape(32, 32, 3, -1).transpose(3, 0, 1, 2)\n", " plt.imshow(visualize_grid(W1, padding=3).astype('uint8'))\n", " plt.gca().axis('off')\n", " plt.show()\n", "\n", "show_net_weights(net)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Tune your hyperparameters\n", "\n", "**What's wrong?**. Looking at the visualizations above, we see that the loss is decreasing more or less linearly, which seems to suggest that the learning rate may be too low. Moreover, there is no gap between the training and validation accuracy, suggesting that the model we used has low capacity, and that we should increase its size. On the other hand, with a very large model we would expect to see more overfitting, which would manifest itself as a very large gap between the training and validation accuracy.\n", "\n", "**Tuning**. Tuning the hyperparameters and developing intuition for how they affect the final performance is a large part of using Neural Networks, so we want you to get a lot of practice. Below, you should experiment with different values of the various hyperparameters, including hidden layer size, learning rate, numer of training epochs, and regularization strength. You might also consider tuning the learning rate decay, but you should be able to get good performance using the default value.\n", "\n", "**Approximate results**. You should be aim to achieve a classification accuracy of greater than 48% on the validation set. Our best network gets over 52% on the validation set.\n", "\n", "**Experiment**: You goal in this exercise is to get as good of a result on CIFAR-10 as you can (52% could serve as a reference), with a fully-connected Neural Network. Feel free implement your own techniques (e.g. PCA to reduce dimensionality, or adding dropout, or adding features to the solver, etc.)." ] }, { "cell_type": "markdown", "metadata": { "tags": [ "pdf-inline" ] }, "source": [ "**Explain your hyperparameter tuning process below.**\n", "\n", "$\\color{blue}{\\textit Your Answer:}$" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "code" ] }, "outputs": [], "source": [ "best_net = None # store the best model into this \n", "\n", "#################################################################################\n", "# TODO: Tune hyperparameters using the validation set. Store your best trained #\n", "# model in best_net. #\n", "# #\n", "# To help debug your network, it may help to use visualizations similar to the #\n", "# ones we used above; these visualizations will have significant qualitative #\n", "# differences from the ones we saw above for the poorly tuned network. #\n", "# #\n", "# Tweaking hyperparameters by hand can be fun, but you might find it useful to #\n", "# write code to sweep through possible combinations of hyperparameters #\n", "# automatically like we did on the previous exercises. #\n", "#################################################################################\n", "# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n", "pass\n", "\n# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# visualize the weights of the best network\n", "show_net_weights(best_net)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Run on the test set\n", "When you are done experimenting, you should evaluate your final trained network on the test set; you should get above 48%." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "test_acc = (best_net.predict(X_test) == y_test).mean()\n", "print('Test accuracy: ', test_acc)" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "pdf-inline" ] }, "source": [ "**Inline Question**\n", "\n", "Now that you have trained a Neural Network classifier, you may find that your testing accuracy is much lower than the training accuracy. In what ways can we decrease this gap? Select all that apply.\n", "\n", "1. Train on a larger dataset.\n", "2. Add more hidden units.\n", "3. Increase the regularization strength.\n", "4. None of the above.\n", "\n", "$\\color{blue}{\\textit Your Answer:}$\n", "\n", "$\\color{blue}{\\textit Your Explanation:}$\n", "\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.7.1" } }, "nbformat": 4, "nbformat_minor": 1 }