Fully-Connected Neural Nets

In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures.

In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a forward and a backward function. The forward function will receive inputs, weights, and other parameters and will return both an output and a cache object storing data needed for the backward pass, like this:

def layer_forward(x, w):
  """ Receive inputs x and weights w """
  # Do some computations ...
  z = # ... some intermediate value
  # Do some more computations ...
  out = # the output

  cache = (x, w, z, out) # Values we need to compute gradients

  return out, cache

The backward pass will receive upstream derivatives and the cache object, and will return gradients with respect to the inputs and weights, like this:

def layer_backward(dout, cache):
  """
  Receive derivative of loss with respect to outputs and cache,
  and compute derivative with respect to inputs.
  """
  # Unpack cache values
  x, w, z, out = cache

  # Use values in cache to compute derivatives
  dx = # Derivative of loss with respect to x
  dw = # Derivative of loss with respect to w

  return dx, dw

After implementing a bunch of layers this way, we will be able to easily combine them to build classifiers with different architectures.

In addition to implementing fully-connected networks of arbitrary depth, we will also explore different update rules for optimization, and introduce Dropout as a regularizer and Batch Normalization as a tool to more efficiently optimize deep networks.


In [1]:
# As usual, a bit of setup
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
import time
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.fc_net import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from cs231n.solver import Solver

%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

# for auto-reloading external modules
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2

def rel_error(x, y):
  """ returns relative error """
  return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))


run the following from the cs231n directory and try again:
python setup.py build_ext --inplace
You may also need to restart your iPython kernel
/home/levin/anaconda2/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')

In [2]:
# Load the (preprocessed) CIFAR10 data.

data = get_CIFAR10_data()
for k, v in data.iteritems():
  print '%s: ' % k, v.shape


X_val:  (1000, 3, 32, 32)
X_train:  (49000, 3, 32, 32)
X_test:  (1000, 3, 32, 32)
y_val:  (1000,)
y_train:  (49000,)
y_test:  (1000,)

Affine layer: foward

Open the file cs231n/layers.py and implement the affine_forward function.

Once you are done you can test your implementaion by running the following:


In [3]:
# Test the affine_forward function

num_inputs = 2
input_shape = (4, 5, 6)
output_dim = 3

input_size = num_inputs * np.prod(input_shape)
weight_size = output_dim * np.prod(input_shape)

x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape)
w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim)
b = np.linspace(-0.3, 0.1, num=output_dim)

out, _ = affine_forward(x, w, b)
correct_out = np.array([[ 1.49834967,  1.70660132,  1.91485297],
                        [ 3.25553199,  3.5141327,   3.77273342]])

# Compare your output with ours. The error should be around 1e-9.
print 'Testing affine_forward function:'
print 'difference: ', rel_error(out, correct_out)


Testing affine_forward function:
difference:  9.76984946819e-10

Affine layer: backward

Now implement the affine_backward function and test your implementation using numeric gradient checking.


In [4]:
# Test the affine_backward function

x = np.random.randn(10, 2, 3)
w = np.random.randn(6, 5)
b = np.random.randn(5)
dout = np.random.randn(10, 5)

dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout)
dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout)
db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout)

_, cache = affine_forward(x, w, b)
dx, dw, db = affine_backward(dout, cache)

# The error should be around 1e-10
print 'Testing affine_backward function:'
print 'dx error: ', rel_error(dx_num, dx)
print 'dw error: ', rel_error(dw_num, dw)
print 'db error: ', rel_error(db_num, db)


Testing affine_backward function:
dx error:  2.92895223181e-10
dw error:  2.29474519463e-10
db error:  4.1737760614e-11

ReLU layer: forward

Implement the forward pass for the ReLU activation function in the relu_forward function and test your implementation using the following:


In [5]:
# Test the relu_forward function

x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4)

out, _ = relu_forward(x)
correct_out = np.array([[ 0.,          0.,          0.,          0.,        ],
                        [ 0.,          0.,          0.04545455,  0.13636364,],
                        [ 0.22727273,  0.31818182,  0.40909091,  0.5,       ]])

# Compare your output with ours. The error should be around 1e-8
print 'Testing relu_forward function:'
print 'difference: ', rel_error(out, correct_out)


Testing relu_forward function:
difference:  4.99999979802e-08

ReLU layer: backward

Now implement the backward pass for the ReLU activation function in the relu_backward function and test your implementation using numeric gradient checking:


In [6]:
x = np.random.randn(10, 10)
dout = np.random.randn(*x.shape)

dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout)

_, cache = relu_forward(x)
dx = relu_backward(dout, cache)

# The error should be around 1e-12
print 'Testing relu_backward function:'
print 'dx error: ', rel_error(dx_num, dx)


Testing relu_backward function:
dx error:  3.27561383708e-12

"Sandwich" layers

There are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file cs231n/layer_utils.py.

For now take a look at the affine_relu_forward and affine_relu_backward functions, and run the following to numerically gradient check the backward pass:


In [7]:
from cs231n.layer_utils import affine_relu_forward, affine_relu_backward

x = np.random.randn(2, 3, 4)
w = np.random.randn(12, 10)
b = np.random.randn(10)
dout = np.random.randn(2, 10)

out, cache = affine_relu_forward(x, w, b)
dx, dw, db = affine_relu_backward(dout, cache)

dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout)
dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout)
db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout)

print 'Testing affine_relu_forward:'
print 'dx error: ', rel_error(dx_num, dx)
print 'dw error: ', rel_error(dw_num, dw)
print 'db error: ', rel_error(db_num, db)


Testing affine_relu_forward:
dx error:  4.61025112012e-10
dw error:  1.21121604714e-10
db error:  4.22957555078e-11

Loss layers: Softmax and SVM

You implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in cs231n/layers.py.

You can make sure that the implementations are correct by running the following:


In [8]:
num_classes, num_inputs = 10, 50
x = 0.001 * np.random.randn(num_inputs, num_classes)
y = np.random.randint(num_classes, size=num_inputs)

dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False)
loss, dx = svm_loss(x, y)

# Test svm_loss function. Loss should be around 9 and dx error should be 1e-9
print 'Testing svm_loss:'
print 'loss: ', loss
print 'dx error: ', rel_error(dx_num, dx)

dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False)
loss, dx = softmax_loss(x, y)

# Test softmax_loss function. Loss should be 2.3 and dx error should be 1e-8
print '\nTesting softmax_loss:'
print 'loss: ', loss
print 'dx error: ', rel_error(dx_num, dx)


Testing svm_loss:
loss:  8.9988134813
dx error:  3.62260263876e-09

Testing softmax_loss:
loss:  2.30246686253
dx error:  8.69677164163e-09

Two-layer network

In the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.

Open the file cs231n/classifiers/fc_net.py and complete the implementation of the TwoLayerNet class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation.


In [9]:
N, D, H, C = 3, 5, 50, 7
X = np.random.randn(N, D)
y = np.random.randint(C, size=N)

std = 1e-2
model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std)

print 'Testing initialization ... '
W1_std = abs(model.params['W1'].std() - std)
b1 = model.params['b1']
W2_std = abs(model.params['W2'].std() - std)
b2 = model.params['b2']
assert W1_std < std / 10, 'First layer weights do not seem right'
assert np.all(b1 == 0), 'First layer biases do not seem right'
assert W2_std < std / 10, 'Second layer weights do not seem right'
assert np.all(b2 == 0), 'Second layer biases do not seem right'

print 'Testing test-time forward pass ... '
model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H)
model.params['b1'] = np.linspace(-0.1, 0.9, num=H)
model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C)
model.params['b2'] = np.linspace(-0.9, 0.1, num=C)
X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T
scores = model.loss(X)
correct_scores = np.asarray(
  [[11.53165108,  12.2917344,   13.05181771,  13.81190102,  14.57198434, 15.33206765,  16.09215096],
   [12.05769098,  12.74614105,  13.43459113,  14.1230412,   14.81149128, 15.49994135,  16.18839143],
   [12.58373087,  13.20054771,  13.81736455,  14.43418138,  15.05099822, 15.66781506,  16.2846319 ]])
scores_diff = np.abs(scores - correct_scores).sum()
assert scores_diff < 1e-6, 'Problem with test-time forward pass'

print 'Testing training loss (no regularization)'
y = np.asarray([0, 5, 1])
loss, grads = model.loss(X, y)
correct_loss = 3.4702243556
assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss'

model.reg = 1.0
loss, grads = model.loss(X, y)
correct_loss = 26.5948426952
assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss'

for reg in [0.0, 0.7]:
  print 'Running numeric gradient check with reg = ', reg
  model.reg = reg
  loss, grads = model.loss(X, y)

  for name in sorted(grads):
    f = lambda _: model.loss(X, y)[0]
    grad_num = eval_numerical_gradient(f, model.params[name], verbose=False)
    print '%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))


Testing initialization ... 
Testing test-time forward pass ... 
Testing training loss (no regularization)
Running numeric gradient check with reg =  0.0
W1 relative error: 1.83e-08
W2 relative error: 3.20e-10
b1 relative error: 9.83e-09
b2 relative error: 4.33e-10
Running numeric gradient check with reg =  0.7
W1 relative error: 2.53e-07
W2 relative error: 2.85e-08
b1 relative error: 1.56e-08
b2 relative error: 9.09e-10

Solver

In the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.

Open the file cs231n/solver.py and read through it to familiarize yourself with the API. After doing so, use a Solver instance to train a TwoLayerNet that achieves at least 50% accuracy on the validation set.


In [11]:
# model = TwoLayerNet()
# solver = None

##############################################################################
# TODO: Use a Solver instance to train a TwoLayerNet that achieves at least  #
# 50% accuracy on the validation set.                                        #
##############################################################################
input_dim=3*32*32
hidden_dim=100
num_classes=10
weight_scale=1e-3
reg=0.0
model = TwoLayerNet(input_dim=input_dim, hidden_dim=hidden_dim, num_classes=num_classes,
                     weight_scale=weight_scale, reg=reg)

solver = Solver(model, data,
                            update_rule='sgd',
                            optim_config={
                                'learning_rate': 1e-3,
                            },
                            lr_decay=0.95,
                            num_epochs=10, batch_size=100,
                            print_every=100)
solver.train()
##############################################################################
#                             END OF YOUR CODE                               #
##############################################################################


(Iteration 1 / 4900) loss: 2.299175
(Epoch 0 / 10) train acc: 0.132000; val_acc: 0.114000
(Iteration 101 / 4900) loss: 1.745887
(Iteration 201 / 4900) loss: 1.841234
(Iteration 301 / 4900) loss: 1.469272
(Iteration 401 / 4900) loss: 1.459521
(Epoch 1 / 10) train acc: 0.442000; val_acc: 0.431000
(Iteration 501 / 4900) loss: 1.686477
(Iteration 601 / 4900) loss: 1.548239
(Iteration 701 / 4900) loss: 1.341739
(Iteration 801 / 4900) loss: 1.622524
(Iteration 901 / 4900) loss: 1.412256
(Epoch 2 / 10) train acc: 0.481000; val_acc: 0.471000
(Iteration 1001 / 4900) loss: 1.528274
(Iteration 1101 / 4900) loss: 1.430866
(Iteration 1201 / 4900) loss: 1.701945
(Iteration 1301 / 4900) loss: 1.355894
(Iteration 1401 / 4900) loss: 1.429757
(Epoch 3 / 10) train acc: 0.494000; val_acc: 0.473000
(Iteration 1501 / 4900) loss: 1.578617
(Iteration 1601 / 4900) loss: 1.404213
(Iteration 1701 / 4900) loss: 1.174549
(Iteration 1801 / 4900) loss: 1.319764
(Iteration 1901 / 4900) loss: 1.337004
(Epoch 4 / 10) train acc: 0.552000; val_acc: 0.485000
(Iteration 2001 / 4900) loss: 1.446253
(Iteration 2101 / 4900) loss: 1.512710
(Iteration 2201 / 4900) loss: 1.179128
(Iteration 2301 / 4900) loss: 1.237280
(Iteration 2401 / 4900) loss: 1.335179
(Epoch 5 / 10) train acc: 0.557000; val_acc: 0.490000
(Iteration 2501 / 4900) loss: 1.334219
(Iteration 2601 / 4900) loss: 1.292154
(Iteration 2701 / 4900) loss: 1.307421
(Iteration 2801 / 4900) loss: 1.261683
(Iteration 2901 / 4900) loss: 1.259764
(Epoch 6 / 10) train acc: 0.555000; val_acc: 0.505000
(Iteration 3001 / 4900) loss: 1.315673
(Iteration 3101 / 4900) loss: 1.237905
(Iteration 3201 / 4900) loss: 1.123620
(Iteration 3301 / 4900) loss: 1.053664
(Iteration 3401 / 4900) loss: 1.135636
(Epoch 7 / 10) train acc: 0.568000; val_acc: 0.495000
(Iteration 3501 / 4900) loss: 1.258151
(Iteration 3601 / 4900) loss: 0.986172
(Iteration 3701 / 4900) loss: 1.146398
(Iteration 3801 / 4900) loss: 1.087954
(Iteration 3901 / 4900) loss: 1.049108
(Epoch 8 / 10) train acc: 0.597000; val_acc: 0.522000
(Iteration 4001 / 4900) loss: 1.198095
(Iteration 4101 / 4900) loss: 1.152446
(Iteration 4201 / 4900) loss: 1.097323
(Iteration 4301 / 4900) loss: 1.230197
(Iteration 4401 / 4900) loss: 1.170906
(Epoch 9 / 10) train acc: 0.599000; val_acc: 0.493000
(Iteration 4501 / 4900) loss: 0.976991
(Iteration 4601 / 4900) loss: 1.412240
(Iteration 4701 / 4900) loss: 1.181796
(Iteration 4801 / 4900) loss: 1.224346
(Epoch 10 / 10) train acc: 0.595000; val_acc: 0.511000

In [12]:
# Run this cell to visualize training loss and train / val accuracy

plt.subplot(2, 1, 1)
plt.title('Training loss')
plt.plot(solver.loss_history, 'o')
plt.xlabel('Iteration')

plt.subplot(2, 1, 2)
plt.title('Accuracy')
plt.plot(solver.train_acc_history, '-o', label='train')
plt.plot(solver.val_acc_history, '-o', label='val')
plt.plot([0.5] * len(solver.val_acc_history), 'k--')
plt.xlabel('Epoch')
plt.legend(loc='lower right')
plt.gcf().set_size_inches(15, 12)
plt.show()


Multilayer network

Next you will implement a fully-connected network with an arbitrary number of hidden layers.

Read through the FullyConnectedNet class in the file cs231n/classifiers/fc_net.py.

Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch normalization; we will add those features soon.

Initial loss and gradient check

As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?

For gradient checking, you should expect to see errors around 1e-6 or less.


In [13]:
N, D, H1, H2, C = 2, 15, 20, 30, 10
X = np.random.randn(N, D)
y = np.random.randint(C, size=(N,))

for reg in [0, 3.14]:
  print 'Running check with reg = ', reg
  model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C,
                            reg=reg, weight_scale=5e-2, dtype=np.float64)

  loss, grads = model.loss(X, y)
  print 'Initial loss: ', loss

  for name in sorted(grads):
    f = lambda _: model.loss(X, y)[0]
    grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5)
    print '%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))


Running check with reg =  0
Initial loss:  2.30215742661
W1 relative error: 1.61e-06
W2 relative error: 6.56e-07
W3 relative error: 2.36e-07
b1 relative error: 7.68e-08
b2 relative error: 1.39e-08
b3 relative error: 1.11e-10
Running check with reg =  3.14
Initial loss:  6.82186799419
W1 relative error: 1.33e-07
W2 relative error: 2.15e-08
W3 relative error: 1.76e-08
b1 relative error: 1.31e-07
b2 relative error: 1.92e-08
b3 relative error: 2.75e-10

As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs.


In [19]:
# TODO: Use a three-layer Net to overfit 50 training examples.

num_train = 50
small_data = {
  'X_train': data['X_train'][:num_train],
  'y_train': data['y_train'][:num_train],
  'X_val': data['X_val'],
  'y_val': data['y_val'],
}

learning_rate = 1e-2
weight_scale = 1e-2
model = FullyConnectedNet([100, 100],
              weight_scale=weight_scale, dtype=np.float64)
solver = Solver(model, small_data,
                print_every=10, num_epochs=20, batch_size=25,
                update_rule='sgd',
                optim_config={
                  'learning_rate': learning_rate,
                }
         )
solver.train()

plt.plot(solver.loss_history, 'o')
plt.title('Training loss history')
plt.xlabel('Iteration')
plt.ylabel('Training loss')
plt.show()


(Iteration 1 / 40) loss: 2.290972
(Epoch 0 / 20) train acc: 0.260000; val_acc: 0.118000
(Epoch 1 / 20) train acc: 0.360000; val_acc: 0.140000
(Epoch 2 / 20) train acc: 0.340000; val_acc: 0.136000
(Epoch 3 / 20) train acc: 0.540000; val_acc: 0.140000
(Epoch 4 / 20) train acc: 0.340000; val_acc: 0.134000
(Epoch 5 / 20) train acc: 0.740000; val_acc: 0.190000
(Iteration 11 / 40) loss: 1.386780
(Epoch 6 / 20) train acc: 0.780000; val_acc: 0.188000
(Epoch 7 / 20) train acc: 0.720000; val_acc: 0.163000
(Epoch 8 / 20) train acc: 0.560000; val_acc: 0.132000
(Epoch 9 / 20) train acc: 0.840000; val_acc: 0.173000
(Epoch 10 / 20) train acc: 0.940000; val_acc: 0.189000
(Iteration 21 / 40) loss: 0.334002
(Epoch 11 / 20) train acc: 0.960000; val_acc: 0.207000
(Epoch 12 / 20) train acc: 0.940000; val_acc: 0.208000
(Epoch 13 / 20) train acc: 0.980000; val_acc: 0.212000
(Epoch 14 / 20) train acc: 1.000000; val_acc: 0.203000
(Epoch 15 / 20) train acc: 0.980000; val_acc: 0.214000
(Iteration 31 / 40) loss: 0.046344
(Epoch 16 / 20) train acc: 1.000000; val_acc: 0.199000
(Epoch 17 / 20) train acc: 1.000000; val_acc: 0.208000
(Epoch 18 / 20) train acc: 1.000000; val_acc: 0.206000
(Epoch 19 / 20) train acc: 1.000000; val_acc: 0.206000
(Epoch 20 / 20) train acc: 1.000000; val_acc: 0.204000

Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs.


In [25]:
# TODO: Use a five-layer Net to overfit 50 training examples.

num_train = 50
small_data = {
  'X_train': data['X_train'][:num_train],
  'y_train': data['y_train'][:num_train],
  'X_val': data['X_val'],
  'y_val': data['y_val'],
}

learning_rate = 1e-2
weight_scale = 6e-2
model = FullyConnectedNet([100, 100, 100, 100],
                weight_scale=weight_scale, dtype=np.float64)
solver = Solver(model, small_data,
                print_every=10, num_epochs=20, batch_size=25,
                update_rule='sgd',
                optim_config={
                  'learning_rate': learning_rate,
                }
         )
solver.train()

plt.plot(solver.loss_history, 'o')
plt.title('Training loss history')
plt.xlabel('Iteration')
plt.ylabel('Training loss')
plt.show()


(Iteration 1 / 40) loss: 8.685991
(Epoch 0 / 20) train acc: 0.300000; val_acc: 0.092000
(Epoch 1 / 20) train acc: 0.140000; val_acc: 0.107000
(Epoch 2 / 20) train acc: 0.200000; val_acc: 0.127000
(Epoch 3 / 20) train acc: 0.540000; val_acc: 0.108000
(Epoch 4 / 20) train acc: 0.740000; val_acc: 0.147000
(Epoch 5 / 20) train acc: 0.820000; val_acc: 0.139000
(Iteration 11 / 40) loss: 0.407608
(Epoch 6 / 20) train acc: 0.880000; val_acc: 0.140000
(Epoch 7 / 20) train acc: 0.960000; val_acc: 0.144000
(Epoch 8 / 20) train acc: 0.980000; val_acc: 0.132000
(Epoch 9 / 20) train acc: 0.980000; val_acc: 0.133000
(Epoch 10 / 20) train acc: 0.980000; val_acc: 0.141000
(Iteration 21 / 40) loss: 0.271167
(Epoch 11 / 20) train acc: 0.980000; val_acc: 0.130000
(Epoch 12 / 20) train acc: 1.000000; val_acc: 0.134000
(Epoch 13 / 20) train acc: 1.000000; val_acc: 0.133000
(Epoch 14 / 20) train acc: 1.000000; val_acc: 0.132000
(Epoch 15 / 20) train acc: 1.000000; val_acc: 0.137000
(Iteration 31 / 40) loss: 0.099823
(Epoch 16 / 20) train acc: 1.000000; val_acc: 0.133000
(Epoch 17 / 20) train acc: 1.000000; val_acc: 0.134000
(Epoch 18 / 20) train acc: 1.000000; val_acc: 0.129000
(Epoch 19 / 20) train acc: 1.000000; val_acc: 0.139000
(Epoch 20 / 20) train acc: 1.000000; val_acc: 0.139000

Inline question:

Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net?

Answer:

It's much harder to find the right weight initialization and learning rate for five layer net. As the network grows deeper, we tend to have more dead activations, and thus kill the backward gradient.

Update rules

So far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD.

SGD+Momentum

Stochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochstic gradient descent.

Open the file cs231n/optim.py and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function sgd_momentum and run the following to check your implementation. You should see errors less than 1e-8.


In [26]:
from cs231n.optim import sgd_momentum

N, D = 4, 5
w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D)
dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D)
v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D)

config = {'learning_rate': 1e-3, 'velocity': v}
next_w, _ = sgd_momentum(w, dw, config=config)

expected_next_w = np.asarray([
  [ 0.1406,      0.20738947,  0.27417895,  0.34096842,  0.40775789],
  [ 0.47454737,  0.54133684,  0.60812632,  0.67491579,  0.74170526],
  [ 0.80849474,  0.87528421,  0.94207368,  1.00886316,  1.07565263],
  [ 1.14244211,  1.20923158,  1.27602105,  1.34281053,  1.4096    ]])
expected_velocity = np.asarray([
  [ 0.5406,      0.55475789,  0.56891579, 0.58307368,  0.59723158],
  [ 0.61138947,  0.62554737,  0.63970526,  0.65386316,  0.66802105],
  [ 0.68217895,  0.69633684,  0.71049474,  0.72465263,  0.73881053],
  [ 0.75296842,  0.76712632,  0.78128421,  0.79544211,  0.8096    ]])

print 'next_w error: ', rel_error(next_w, expected_next_w)
print 'velocity error: ', rel_error(expected_velocity, config['velocity'])


next_w error:  8.88234703351e-09
velocity error:  4.26928774328e-09

Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster.


In [27]:
num_train = 4000
small_data = {
  'X_train': data['X_train'][:num_train],
  'y_train': data['y_train'][:num_train],
  'X_val': data['X_val'],
  'y_val': data['y_val'],
}

solvers = {}

for update_rule in ['sgd', 'sgd_momentum']:
  print 'running with ', update_rule
  model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2)

  solver = Solver(model, small_data,
                  num_epochs=5, batch_size=100,
                  update_rule=update_rule,
                  optim_config={
                    'learning_rate': 1e-2,
                  },
                  verbose=True)
  solvers[update_rule] = solver
  solver.train()
  print

plt.subplot(3, 1, 1)
plt.title('Training loss')
plt.xlabel('Iteration')

plt.subplot(3, 1, 2)
plt.title('Training accuracy')
plt.xlabel('Epoch')

plt.subplot(3, 1, 3)
plt.title('Validation accuracy')
plt.xlabel('Epoch')

for update_rule, solver in solvers.iteritems():
  plt.subplot(3, 1, 1)
  plt.plot(solver.loss_history, 'o', label=update_rule)
  
  plt.subplot(3, 1, 2)
  plt.plot(solver.train_acc_history, '-o', label=update_rule)

  plt.subplot(3, 1, 3)
  plt.plot(solver.val_acc_history, '-o', label=update_rule)
  
for i in [1, 2, 3]:
  plt.subplot(3, 1, i)
  plt.legend(loc='upper center', ncol=4)
plt.gcf().set_size_inches(15, 15)
plt.show()


running with  sgd
(Iteration 1 / 200) loss: 3.163584
(Epoch 0 / 5) train acc: 0.120000; val_acc: 0.133000
(Iteration 11 / 200) loss: 2.147519
(Iteration 21 / 200) loss: 2.134634
(Iteration 31 / 200) loss: 2.061858
(Epoch 1 / 5) train acc: 0.274000; val_acc: 0.258000
(Iteration 41 / 200) loss: 2.079632
(Iteration 51 / 200) loss: 1.965506
(Iteration 61 / 200) loss: 1.838539
(Iteration 71 / 200) loss: 1.967392
(Epoch 2 / 5) train acc: 0.352000; val_acc: 0.306000
(Iteration 81 / 200) loss: 1.837021
(Iteration 91 / 200) loss: 1.964120
(Iteration 101 / 200) loss: 1.848202
(Iteration 111 / 200) loss: 1.715296
(Epoch 3 / 5) train acc: 0.356000; val_acc: 0.323000
(Iteration 121 / 200) loss: 1.679853
(Iteration 131 / 200) loss: 1.830533
(Iteration 141 / 200) loss: 1.956518
(Iteration 151 / 200) loss: 1.767289
(Epoch 4 / 5) train acc: 0.417000; val_acc: 0.319000
(Iteration 161 / 200) loss: 1.718786
(Iteration 171 / 200) loss: 1.633583
(Iteration 181 / 200) loss: 1.552179
(Iteration 191 / 200) loss: 1.589140
(Epoch 5 / 5) train acc: 0.420000; val_acc: 0.337000

running with  sgd_momentum
(Iteration 1 / 200) loss: 2.734394
(Epoch 0 / 5) train acc: 0.150000; val_acc: 0.145000
(Iteration 11 / 200) loss: 2.118655
(Iteration 21 / 200) loss: 1.921783
(Iteration 31 / 200) loss: 1.844981
(Epoch 1 / 5) train acc: 0.256000; val_acc: 0.278000
(Iteration 41 / 200) loss: 1.872145
(Iteration 51 / 200) loss: 1.878514
(Iteration 61 / 200) loss: 1.812046
(Iteration 71 / 200) loss: 1.832228
(Epoch 2 / 5) train acc: 0.382000; val_acc: 0.327000
(Iteration 81 / 200) loss: 1.541768
(Iteration 91 / 200) loss: 1.757576
(Iteration 101 / 200) loss: 1.698475
(Iteration 111 / 200) loss: 1.757442
(Epoch 3 / 5) train acc: 0.459000; val_acc: 0.356000
(Iteration 121 / 200) loss: 1.538579
(Iteration 131 / 200) loss: 1.507526
(Iteration 141 / 200) loss: 1.456616
(Iteration 151 / 200) loss: 1.301375
(Epoch 4 / 5) train acc: 0.513000; val_acc: 0.360000
(Iteration 161 / 200) loss: 1.413942
(Iteration 171 / 200) loss: 1.516297
(Iteration 181 / 200) loss: 1.273159
(Iteration 191 / 200) loss: 1.249190
(Epoch 5 / 5) train acc: 0.496000; val_acc: 0.359000

RMSProp and Adam

RMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.

In the file cs231n/optim.py, implement the RMSProp update rule in the rmsprop function and implement the Adam update rule in the adam function, and check your implementations using the tests below.

[1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).

[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015.


In [28]:
# Test RMSProp implementation; you should see errors less than 1e-7
from cs231n.optim import rmsprop

N, D = 4, 5
w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D)
dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D)
cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D)

config = {'learning_rate': 1e-2, 'cache': cache}
next_w, _ = rmsprop(w, dw, config=config)

expected_next_w = np.asarray([
  [-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247],
  [-0.132737,   -0.08078555, -0.02881884,  0.02316247,  0.07515774],
  [ 0.12716641,  0.17918792,  0.23122175,  0.28326742,  0.33532447],
  [ 0.38739248,  0.43947102,  0.49155973,  0.54365823,  0.59576619]])
expected_cache = np.asarray([
  [ 0.5976,      0.6126277,   0.6277108,   0.64284931,  0.65804321],
  [ 0.67329252,  0.68859723,  0.70395734,  0.71937285,  0.73484377],
  [ 0.75037008,  0.7659518,   0.78158892,  0.79728144,  0.81302936],
  [ 0.82883269,  0.84469141,  0.86060554,  0.87657507,  0.8926    ]])

print 'next_w error: ', rel_error(expected_next_w, next_w)
print 'cache error: ', rel_error(expected_cache, config['cache'])


next_w error:  9.52468751104e-08
cache error:  2.64779558072e-09

In [29]:
# Test Adam implementation; you should see errors around 1e-7 or less
from cs231n.optim import adam

N, D = 4, 5
w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D)
dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D)
m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D)
v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D)

config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5}
next_w, _ = adam(w, dw, config=config)

expected_next_w = np.asarray([
  [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977],
  [-0.1380274,  -0.08544591, -0.03286534,  0.01971428,  0.0722929],
  [ 0.1248705,   0.17744702,  0.23002243,  0.28259667,  0.33516969],
  [ 0.38774145,  0.44031188,  0.49288093,  0.54544852,  0.59801459]])
expected_v = np.asarray([
  [ 0.69966,     0.68908382,  0.67851319,  0.66794809,  0.65738853,],
  [ 0.64683452,  0.63628604,  0.6257431,   0.61520571,  0.60467385,],
  [ 0.59414753,  0.58362676,  0.57311152,  0.56260183,  0.55209767,],
  [ 0.54159906,  0.53110598,  0.52061845,  0.51013645,  0.49966,   ]])
expected_m = np.asarray([
  [ 0.48,        0.49947368,  0.51894737,  0.53842105,  0.55789474],
  [ 0.57736842,  0.59684211,  0.61631579,  0.63578947,  0.65526316],
  [ 0.67473684,  0.69421053,  0.71368421,  0.73315789,  0.75263158],
  [ 0.77210526,  0.79157895,  0.81105263,  0.83052632,  0.85      ]])

print 'next_w error: ', rel_error(expected_next_w, next_w)
print 'v error: ', rel_error(expected_v, config['v'])
print 'm error: ', rel_error(expected_m, config['m'])


next_w error:  1.13956917985e-07
v error:  4.20831403811e-09
m error:  4.21496319311e-09

Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules:


In [30]:
learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3}
for update_rule in ['adam', 'rmsprop']:
  print 'running with ', update_rule
  model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2)

  solver = Solver(model, small_data,
                  num_epochs=5, batch_size=100,
                  update_rule=update_rule,
                  optim_config={
                    'learning_rate': learning_rates[update_rule]
                  },
                  verbose=True)
  solvers[update_rule] = solver
  solver.train()
  print

plt.subplot(3, 1, 1)
plt.title('Training loss')
plt.xlabel('Iteration')

plt.subplot(3, 1, 2)
plt.title('Training accuracy')
plt.xlabel('Epoch')

plt.subplot(3, 1, 3)
plt.title('Validation accuracy')
plt.xlabel('Epoch')

for update_rule, solver in solvers.iteritems():
  plt.subplot(3, 1, 1)
  plt.plot(solver.loss_history, 'o', label=update_rule)
  
  plt.subplot(3, 1, 2)
  plt.plot(solver.train_acc_history, '-o', label=update_rule)

  plt.subplot(3, 1, 3)
  plt.plot(solver.val_acc_history, '-o', label=update_rule)
  
for i in [1, 2, 3]:
  plt.subplot(3, 1, i)
  plt.legend(loc='upper center', ncol=4)
plt.gcf().set_size_inches(15, 15)
plt.show()


running with  adam
(Iteration 1 / 200) loss: 2.705596
(Epoch 0 / 5) train acc: 0.138000; val_acc: 0.123000
(Iteration 11 / 200) loss: 2.133164
(Iteration 21 / 200) loss: 2.090119
(Iteration 31 / 200) loss: 1.924945
(Epoch 1 / 5) train acc: 0.359000; val_acc: 0.287000
(Iteration 41 / 200) loss: 1.667574
(Iteration 51 / 200) loss: 1.777399
(Iteration 61 / 200) loss: 1.653608
(Iteration 71 / 200) loss: 1.579225
(Epoch 2 / 5) train acc: 0.435000; val_acc: 0.336000
(Iteration 81 / 200) loss: 1.481105
(Iteration 91 / 200) loss: 1.526769
(Iteration 101 / 200) loss: 1.461250
(Iteration 111 / 200) loss: 1.430679
(Epoch 3 / 5) train acc: 0.474000; val_acc: 0.362000
(Iteration 121 / 200) loss: 1.448526
(Iteration 131 / 200) loss: 1.546457
(Iteration 141 / 200) loss: 1.396395
(Iteration 151 / 200) loss: 1.579234
(Epoch 4 / 5) train acc: 0.546000; val_acc: 0.376000
(Iteration 161 / 200) loss: 1.205349
(Iteration 171 / 200) loss: 1.374671
(Iteration 181 / 200) loss: 1.161410
(Iteration 191 / 200) loss: 1.267196
(Epoch 5 / 5) train acc: 0.575000; val_acc: 0.375000

running with  rmsprop
(Iteration 1 / 200) loss: 2.815276
(Epoch 0 / 5) train acc: 0.123000; val_acc: 0.127000
(Iteration 11 / 200) loss: 2.066750
(Iteration 21 / 200) loss: 2.089666
(Iteration 31 / 200) loss: 1.916847
(Epoch 1 / 5) train acc: 0.389000; val_acc: 0.285000
(Iteration 41 / 200) loss: 1.797897
(Iteration 51 / 200) loss: 1.828609
(Iteration 61 / 200) loss: 1.780695
(Iteration 71 / 200) loss: 1.702990
(Epoch 2 / 5) train acc: 0.427000; val_acc: 0.310000
(Iteration 81 / 200) loss: 1.829711
(Iteration 91 / 200) loss: 1.611500
(Iteration 101 / 200) loss: 1.522065
(Iteration 111 / 200) loss: 1.548703
(Epoch 3 / 5) train acc: 0.456000; val_acc: 0.319000
(Iteration 121 / 200) loss: 1.518567
(Iteration 131 / 200) loss: 1.506497
(Iteration 141 / 200) loss: 1.620115
(Iteration 151 / 200) loss: 1.792177
(Epoch 4 / 5) train acc: 0.484000; val_acc: 0.343000
(Iteration 161 / 200) loss: 1.539174
(Iteration 171 / 200) loss: 1.704846
(Iteration 181 / 200) loss: 1.364234
(Iteration 191 / 200) loss: 1.207458
(Epoch 5 / 5) train acc: 0.534000; val_acc: 0.345000

Train a good model!

Train the best fully-connected model that you can on CIFAR-10, storing your best model in the best_model variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.

If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.

You might find it useful to complete the BatchNormalization.ipynb and Dropout.ipynb notebooks before completing this part, since those techniques can help you train powerful models.


In [31]:
best_model = None
################################################################################
# TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might   #
# batch normalization and dropout useful. Store your best model in the         #
# best_model variable.                                                         #
################################################################################
num_train = data['X_train'].shape[0]
small_data = {
  'X_train': data['X_train'][:num_train],
  'y_train': data['y_train'][:num_train],
  'X_val': data['X_val'],
  'y_val': data['y_val'],
}
dropout=0.1
model = FullyConnectedNet([100, 100, 100], weight_scale=5e-2, use_batchnorm=True, dropout=dropout)

update_rule = 'adam'
learning_rate = 1e-3
solver = Solver(model, small_data,
                num_epochs=5, batch_size=100,
                update_rule=update_rule,
                optim_config={
                  'learning_rate': learning_rate
                },
                verbose=True)
solver.train()
best_model = model
################################################################################
#                              END OF YOUR CODE                                #
################################################################################


(Iteration 1 / 2450) loss: 2.393245
(Epoch 0 / 5) train acc: 0.124000; val_acc: 0.113000
(Iteration 11 / 2450) loss: 2.172244
(Iteration 21 / 2450) loss: 1.935820
(Iteration 31 / 2450) loss: 1.948361
(Iteration 41 / 2450) loss: 1.891365
(Iteration 51 / 2450) loss: 1.795540
(Iteration 61 / 2450) loss: 1.972566
(Iteration 71 / 2450) loss: 1.733027
(Iteration 81 / 2450) loss: 1.818204
(Iteration 91 / 2450) loss: 1.811869
(Iteration 101 / 2450) loss: 1.633671
(Iteration 111 / 2450) loss: 1.881841
(Iteration 121 / 2450) loss: 1.718194
(Iteration 131 / 2450) loss: 1.762939
(Iteration 141 / 2450) loss: 1.719082
(Iteration 151 / 2450) loss: 1.769248
(Iteration 161 / 2450) loss: 1.686924
(Iteration 171 / 2450) loss: 1.636663
(Iteration 181 / 2450) loss: 1.800643
(Iteration 191 / 2450) loss: 1.769995
(Iteration 201 / 2450) loss: 1.619124
(Iteration 211 / 2450) loss: 1.449260
(Iteration 221 / 2450) loss: 1.672231
(Iteration 231 / 2450) loss: 1.759620
(Iteration 241 / 2450) loss: 1.744652
(Iteration 251 / 2450) loss: 1.699259
(Iteration 261 / 2450) loss: 1.457534
(Iteration 271 / 2450) loss: 1.582331
(Iteration 281 / 2450) loss: 1.698536
(Iteration 291 / 2450) loss: 1.712866
(Iteration 301 / 2450) loss: 1.552364
(Iteration 311 / 2450) loss: 1.489530
(Iteration 321 / 2450) loss: 1.477179
(Iteration 331 / 2450) loss: 1.622095
(Iteration 341 / 2450) loss: 1.737046
(Iteration 351 / 2450) loss: 1.657767
(Iteration 361 / 2450) loss: 1.564889
(Iteration 371 / 2450) loss: 1.502038
(Iteration 381 / 2450) loss: 1.421695
(Iteration 391 / 2450) loss: 1.614303
(Iteration 401 / 2450) loss: 1.522058
(Iteration 411 / 2450) loss: 1.448205
(Iteration 421 / 2450) loss: 1.469830
(Iteration 431 / 2450) loss: 1.725102
(Iteration 441 / 2450) loss: 1.607295
(Iteration 451 / 2450) loss: 1.515946
(Iteration 461 / 2450) loss: 1.583637
(Iteration 471 / 2450) loss: 1.595459
(Iteration 481 / 2450) loss: 1.461294
(Epoch 1 / 5) train acc: 0.451000; val_acc: 0.480000
(Iteration 491 / 2450) loss: 1.494689
(Iteration 501 / 2450) loss: 1.661207
(Iteration 511 / 2450) loss: 1.609235
(Iteration 521 / 2450) loss: 1.596649
(Iteration 531 / 2450) loss: 1.572454
(Iteration 541 / 2450) loss: 1.472974
(Iteration 551 / 2450) loss: 1.653810
(Iteration 561 / 2450) loss: 1.523912
(Iteration 571 / 2450) loss: 1.429298
(Iteration 581 / 2450) loss: 1.320026
(Iteration 591 / 2450) loss: 1.448211
(Iteration 601 / 2450) loss: 1.462247
(Iteration 611 / 2450) loss: 1.459668
(Iteration 621 / 2450) loss: 1.574792
(Iteration 631 / 2450) loss: 1.462531
(Iteration 641 / 2450) loss: 1.529277
(Iteration 651 / 2450) loss: 1.434763
(Iteration 661 / 2450) loss: 1.508439
(Iteration 671 / 2450) loss: 1.620399
(Iteration 681 / 2450) loss: 1.633626
(Iteration 691 / 2450) loss: 1.270819
(Iteration 701 / 2450) loss: 1.400894
(Iteration 711 / 2450) loss: 1.454795
(Iteration 721 / 2450) loss: 1.401864
(Iteration 731 / 2450) loss: 1.617353
(Iteration 741 / 2450) loss: 1.530766
(Iteration 751 / 2450) loss: 1.437644
(Iteration 761 / 2450) loss: 1.629797
(Iteration 771 / 2450) loss: 1.502987
(Iteration 781 / 2450) loss: 1.415692
(Iteration 791 / 2450) loss: 1.512322
(Iteration 801 / 2450) loss: 1.564117
(Iteration 811 / 2450) loss: 1.334242
(Iteration 821 / 2450) loss: 1.646106
(Iteration 831 / 2450) loss: 1.466075
(Iteration 841 / 2450) loss: 1.351835
(Iteration 851 / 2450) loss: 1.473896
(Iteration 861 / 2450) loss: 1.505670
(Iteration 871 / 2450) loss: 1.332002
(Iteration 881 / 2450) loss: 1.483209
(Iteration 891 / 2450) loss: 1.441480
(Iteration 901 / 2450) loss: 1.358909
(Iteration 911 / 2450) loss: 1.432335
(Iteration 921 / 2450) loss: 1.512830
(Iteration 931 / 2450) loss: 1.395373
(Iteration 941 / 2450) loss: 1.568875
(Iteration 951 / 2450) loss: 1.484491
(Iteration 961 / 2450) loss: 1.554645
(Iteration 971 / 2450) loss: 1.598657
(Epoch 2 / 5) train acc: 0.518000; val_acc: 0.505000
(Iteration 981 / 2450) loss: 1.618098
(Iteration 991 / 2450) loss: 1.367231
(Iteration 1001 / 2450) loss: 1.484485
(Iteration 1011 / 2450) loss: 1.425154
(Iteration 1021 / 2450) loss: 1.437529
(Iteration 1031 / 2450) loss: 1.509744
(Iteration 1041 / 2450) loss: 1.437439
(Iteration 1051 / 2450) loss: 1.637276
(Iteration 1061 / 2450) loss: 1.369180
(Iteration 1071 / 2450) loss: 1.543416
(Iteration 1081 / 2450) loss: 1.386472
(Iteration 1091 / 2450) loss: 1.434196
(Iteration 1101 / 2450) loss: 1.515242
(Iteration 1111 / 2450) loss: 1.644874
(Iteration 1121 / 2450) loss: 1.275796
(Iteration 1131 / 2450) loss: 1.406213
(Iteration 1141 / 2450) loss: 1.327130
(Iteration 1151 / 2450) loss: 1.596233
(Iteration 1161 / 2450) loss: 1.493404
(Iteration 1171 / 2450) loss: 1.629423
(Iteration 1181 / 2450) loss: 1.433704
(Iteration 1191 / 2450) loss: 1.469942
(Iteration 1201 / 2450) loss: 1.556239
(Iteration 1211 / 2450) loss: 1.355049
(Iteration 1221 / 2450) loss: 1.504717
(Iteration 1231 / 2450) loss: 1.534259
(Iteration 1241 / 2450) loss: 1.406516
(Iteration 1251 / 2450) loss: 1.590167
(Iteration 1261 / 2450) loss: 1.557688
(Iteration 1271 / 2450) loss: 1.275411
(Iteration 1281 / 2450) loss: 1.465114
(Iteration 1291 / 2450) loss: 1.271140
(Iteration 1301 / 2450) loss: 1.415476
(Iteration 1311 / 2450) loss: 1.452175
(Iteration 1321 / 2450) loss: 1.233572
(Iteration 1331 / 2450) loss: 1.453561
(Iteration 1341 / 2450) loss: 1.406712
(Iteration 1351 / 2450) loss: 1.340919
(Iteration 1361 / 2450) loss: 1.436322
(Iteration 1371 / 2450) loss: 1.406518
(Iteration 1381 / 2450) loss: 1.183880
(Iteration 1391 / 2450) loss: 1.343576
(Iteration 1401 / 2450) loss: 1.397365
(Iteration 1411 / 2450) loss: 1.412249
(Iteration 1421 / 2450) loss: 1.286231
(Iteration 1431 / 2450) loss: 1.420857
(Iteration 1441 / 2450) loss: 1.247353
(Iteration 1451 / 2450) loss: 1.404727
(Iteration 1461 / 2450) loss: 1.316732
(Epoch 3 / 5) train acc: 0.542000; val_acc: 0.509000
(Iteration 1471 / 2450) loss: 1.404328
(Iteration 1481 / 2450) loss: 1.393383
(Iteration 1491 / 2450) loss: 1.314270
(Iteration 1501 / 2450) loss: 1.416495
(Iteration 1511 / 2450) loss: 1.315559
(Iteration 1521 / 2450) loss: 1.296240
(Iteration 1531 / 2450) loss: 1.378123
(Iteration 1541 / 2450) loss: 1.372484
(Iteration 1551 / 2450) loss: 1.463777
(Iteration 1561 / 2450) loss: 1.384762
(Iteration 1571 / 2450) loss: 1.310289
(Iteration 1581 / 2450) loss: 1.400576
(Iteration 1591 / 2450) loss: 1.387287
(Iteration 1601 / 2450) loss: 1.550186
(Iteration 1611 / 2450) loss: 1.442151
(Iteration 1621 / 2450) loss: 1.401800
(Iteration 1631 / 2450) loss: 1.220325
(Iteration 1641 / 2450) loss: 1.199102
(Iteration 1651 / 2450) loss: 1.453058
(Iteration 1661 / 2450) loss: 1.351824
(Iteration 1671 / 2450) loss: 1.319342
(Iteration 1681 / 2450) loss: 1.361695
(Iteration 1691 / 2450) loss: 1.482007
(Iteration 1701 / 2450) loss: 1.246076
(Iteration 1711 / 2450) loss: 1.638169
(Iteration 1721 / 2450) loss: 1.246328
(Iteration 1731 / 2450) loss: 1.569023
(Iteration 1741 / 2450) loss: 1.289674
(Iteration 1751 / 2450) loss: 1.232405
(Iteration 1761 / 2450) loss: 1.195796
(Iteration 1771 / 2450) loss: 1.433443
(Iteration 1781 / 2450) loss: 1.139838
(Iteration 1791 / 2450) loss: 1.206636
(Iteration 1801 / 2450) loss: 1.269741
(Iteration 1811 / 2450) loss: 1.270724
(Iteration 1821 / 2450) loss: 1.252650
(Iteration 1831 / 2450) loss: 1.383356
(Iteration 1841 / 2450) loss: 1.485217
(Iteration 1851 / 2450) loss: 1.221843
(Iteration 1861 / 2450) loss: 1.297372
(Iteration 1871 / 2450) loss: 1.351993
(Iteration 1881 / 2450) loss: 1.304564
(Iteration 1891 / 2450) loss: 1.328241
(Iteration 1901 / 2450) loss: 1.285023
(Iteration 1911 / 2450) loss: 1.432926
(Iteration 1921 / 2450) loss: 1.460258
(Iteration 1931 / 2450) loss: 1.394505
(Iteration 1941 / 2450) loss: 1.315463
(Iteration 1951 / 2450) loss: 1.382753
(Epoch 4 / 5) train acc: 0.546000; val_acc: 0.525000
(Iteration 1961 / 2450) loss: 1.409585
(Iteration 1971 / 2450) loss: 1.268464
(Iteration 1981 / 2450) loss: 1.278014
(Iteration 1991 / 2450) loss: 1.214101
(Iteration 2001 / 2450) loss: 1.354110
(Iteration 2011 / 2450) loss: 1.212669
(Iteration 2021 / 2450) loss: 1.443707
(Iteration 2031 / 2450) loss: 1.322949
(Iteration 2041 / 2450) loss: 1.220443
(Iteration 2051 / 2450) loss: 1.245847
(Iteration 2061 / 2450) loss: 1.406653
(Iteration 2071 / 2450) loss: 1.168552
(Iteration 2081 / 2450) loss: 1.144171
(Iteration 2091 / 2450) loss: 1.335821
(Iteration 2101 / 2450) loss: 1.296504
(Iteration 2111 / 2450) loss: 1.482875
(Iteration 2121 / 2450) loss: 1.325576
(Iteration 2131 / 2450) loss: 1.415418
(Iteration 2141 / 2450) loss: 1.262403
(Iteration 2151 / 2450) loss: 1.341821
(Iteration 2161 / 2450) loss: 1.433409
(Iteration 2171 / 2450) loss: 1.238393
(Iteration 2181 / 2450) loss: 1.296973
(Iteration 2191 / 2450) loss: 1.304204
(Iteration 2201 / 2450) loss: 1.329396
(Iteration 2211 / 2450) loss: 1.297929
(Iteration 2221 / 2450) loss: 1.455924
(Iteration 2231 / 2450) loss: 1.364676
(Iteration 2241 / 2450) loss: 1.134725
(Iteration 2251 / 2450) loss: 1.353628
(Iteration 2261 / 2450) loss: 1.331022
(Iteration 2271 / 2450) loss: 1.369687
(Iteration 2281 / 2450) loss: 1.365139
(Iteration 2291 / 2450) loss: 1.341802
(Iteration 2301 / 2450) loss: 1.446997
(Iteration 2311 / 2450) loss: 1.288457
(Iteration 2321 / 2450) loss: 1.197436
(Iteration 2331 / 2450) loss: 1.280263
(Iteration 2341 / 2450) loss: 1.272699
(Iteration 2351 / 2450) loss: 1.356410
(Iteration 2361 / 2450) loss: 1.301361
(Iteration 2371 / 2450) loss: 1.258524
(Iteration 2381 / 2450) loss: 1.369351
(Iteration 2391 / 2450) loss: 1.372183
(Iteration 2401 / 2450) loss: 1.471954
(Iteration 2411 / 2450) loss: 1.384708
(Iteration 2421 / 2450) loss: 1.322077
(Iteration 2431 / 2450) loss: 1.366167
(Iteration 2441 / 2450) loss: 1.150555
(Epoch 5 / 5) train acc: 0.577000; val_acc: 0.521000

Test you model

Run your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set.


In [33]:
X_test = data['X_test']
y_test = data['y_test']
X_val = data['X_val']
y_val = data['y_val']
y_test_pred = np.argmax(best_model.loss(X_test), axis=1)
y_val_pred = np.argmax(best_model.loss(X_val), axis=1)
print 'Validation set accuracy: ', (y_val_pred == y_val).mean()
print 'Test set accuracy: ', (y_test_pred == y_test).mean()


Validation set accuracy:  0.524
Test set accuracy:  0.52

In [ ]: