Your first neural network

In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and the model more.


In [33]:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Load and prepare the data

A critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon!


In [34]:
data_path = 'Bike-Sharing-Dataset/hour.csv'

rides = pd.read_csv(data_path)

In [35]:
rides.head()


Out[35]:
instant dteday season yr mnth hr holiday weekday workingday weathersit temp atemp hum windspeed casual registered cnt
0 1 2011-01-01 1 0 1 0 0 6 0 1 0.24 0.2879 0.81 0.0 3 13 16
1 2 2011-01-01 1 0 1 1 0 6 0 1 0.22 0.2727 0.80 0.0 8 32 40
2 3 2011-01-01 1 0 1 2 0 6 0 1 0.22 0.2727 0.80 0.0 5 27 32
3 4 2011-01-01 1 0 1 3 0 6 0 1 0.24 0.2879 0.75 0.0 3 10 13
4 5 2011-01-01 1 0 1 4 0 6 0 1 0.24 0.2879 0.75 0.0 0 1 1

Checking out the data

This dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012. The number of riders is split between casual and registered, summed up in the cnt column. You can see the first few rows of the data above.

Below is a plot showing the number of bike riders over the first 10 days or so in the data set. (Some days don't have exactly 24 entries in the data set, so it's not exactly 10 days.) You can see the hourly rentals here. This data is pretty complicated! The weekends have lower over all ridership and there are spikes when people are biking to and from work during the week. Looking at the data above, we also have information about temperature, humidity, and windspeed, all of these likely affecting the number of riders. You'll be trying to capture all this with your model.


In [36]:
rides[:24*10].plot(x='dteday', y='cnt')


Out[36]:
<matplotlib.axes._subplots.AxesSubplot at 0x118cb0dd8>

Dummy variables

Here we have some categorical variables like season, weather, month. To include these in our model, we'll need to make binary dummy variables. This is simple to do with Pandas thanks to get_dummies().


In [37]:
dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday']
for each in dummy_fields:
    dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False)
    rides = pd.concat([rides, dummies], axis=1)

fields_to_drop = ['instant', 'dteday', 'season', 'weathersit', 
                  'weekday', 'atemp', 'mnth', 'workingday', 'hr']
data = rides.drop(fields_to_drop, axis=1)
data.head()


Out[37]:
yr holiday temp hum windspeed casual registered cnt season_1 season_2 ... hr_21 hr_22 hr_23 weekday_0 weekday_1 weekday_2 weekday_3 weekday_4 weekday_5 weekday_6
0 0 0 0.24 0.81 0.0 3 13 16 1 0 ... 0 0 0 0 0 0 0 0 0 1
1 0 0 0.22 0.80 0.0 8 32 40 1 0 ... 0 0 0 0 0 0 0 0 0 1
2 0 0 0.22 0.80 0.0 5 27 32 1 0 ... 0 0 0 0 0 0 0 0 0 1
3 0 0 0.24 0.75 0.0 3 10 13 1 0 ... 0 0 0 0 0 0 0 0 0 1
4 0 0 0.24 0.75 0.0 0 1 1 1 0 ... 0 0 0 0 0 0 0 0 0 1

5 rows × 59 columns

Scaling target variables

To make training the network easier, we'll standardize each of the continuous variables. That is, we'll shift and scale the variables such that they have zero mean and a standard deviation of 1.

The scaling factors are saved so we can go backwards when we use the network for predictions.


In [38]:
quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed']
# Store scalings in a dictionary so we can convert back later
scaled_features = {}
for each in quant_features:
    mean, std = data[each].mean(), data[each].std()
    scaled_features[each] = [mean, std]
    data.loc[:, each] = (data[each] - mean)/std

Splitting the data into training, testing, and validation sets

We'll save the data for the last approximately 21 days to use as a test set after we've trained the network. We'll use this set to make predictions and compare them with the actual number of riders.


In [39]:
# Save data for approximately the last 21 days 
test_data = data[-21*24:]

# Now remove the test data from the data set 
data = data[:-21*24]

# Separate the data into features and targets
target_fields = ['cnt', 'casual', 'registered']
features, targets = data.drop(target_fields, axis=1), data[target_fields]
test_features, test_targets = test_data.drop(target_fields, axis=1), test_data[target_fields]

We'll split the data into two sets, one for training and one for validating as the network is being trained. Since this is time series data, we'll train on historical data, then try to predict on future data (the validation set).


In [40]:
# Hold out the last 60 days or so of the remaining data as a validation set
train_features, train_targets = features[:-60*24], targets[:-60*24]
val_features, val_targets = features[-60*24:], targets[-60*24:]

Time to build the network

Below you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.

The network has two layers, a hidden layer and an output layer. The hidden layer will use the sigmoid function for activations. The output layer has only one node and is used for the regression, the output of the node is the same as the input of the node. That is, the activation function is $f(x)=x$. A function that takes the input signal and generates an output signal, but takes into account the threshold, is called an activation function. We work through each layer of our network calculating the outputs for each neuron. All of the outputs from one layer become inputs to the neurons on the next layer. This process is called forward propagation.

We use the weights to propagate signals forward from the input to the output layers in a neural network. We use the weights to also propagate error backwards from the output back into the network to update our weights. This is called backpropagation.

Hint: You'll need the derivative of the output activation function ($f(x) = x$) for the backpropagation implementation. If you aren't familiar with calculus, this function is equivalent to the equation $y = x$. What is the slope of that equation? That is the derivative of $f(x)$.

Below, you have these tasks:

  1. Implement the sigmoid function to use as the activation function. Set self.activation_function in __init__ to your sigmoid function.
  2. Implement the forward pass in the train method.
  3. Implement the backpropagation algorithm in the train method, including calculating the output error.
  4. Implement the forward pass in the run method.

In [41]:
class NeuralNetwork(object):
    def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
        # Set number of nodes in input, hidden and output layers.

        # D
        self.input_nodes = input_nodes
        # H
        self.hidden_nodes = hidden_nodes
        # C
        self.output_nodes = output_nodes
        
        # Initialize weights
        self.weights_input_to_hidden = np.random.normal(0.0, self.input_nodes**-0.5, 
                                       (self.input_nodes, self.hidden_nodes))

        self.weights_hidden_to_output = np.random.normal(0.0, self.hidden_nodes**-0.5, 
                                       (self.hidden_nodes, self.output_nodes))
        self.lr = learning_rate
        
        #### TODO: Set self.activation_function to your implemented sigmoid function ####
        #
        # Note: in Python, you can define a function with a lambda expression,
        # as shown below.
        self.activation_function = lambda x : 1/(1 + np.exp(-x))  # Replace 0 with your sigmoid calculation.
        
        ### If the lambda code above is not something you're familiar with,
        # You can uncomment out the following three lines and put your 
        # implementation there instead.
        #
        #def sigmoid(x):
        #    return 0  # Replace 0 with your sigmoid calculation here
        #self.activation_function = sigmoid

    def train(self, features, targets):
        return self.train_iterative(features, targets)

        
    # TODO: not sure why the vectorized implementation is incorrect
    def train_vectorized(self, features, targets):
        # self.weights_input_to_hidden.shape W1 (D, H)
        # self.weights_hidden_to_output W2 (H, C)
        # features (N, D)        
        n_records = features.shape[0]
        # hidden_inputs (N, H)
        hidden_inputs = np.dot(features, self.weights_input_to_hidden) # signals into hidden layer
        
        # N, H
        hidden_outputs = self.activation_function(hidden_inputs)
        
        # N, C = (N, H) dot (H, C)
        final_inputs = np.dot(hidden_outputs, self.weights_hidden_to_output) # signals into final output layer
        final_outputs = final_inputs # signals from final output layer

        # (N, C)
#         print(targets.shape, final_outputs.shape)
#         print(targets, final_outputs)
#         raise 'test'
        error = targets - final_outputs
        
        # (H, C)
        self.weights_hidden_to_output += self.lr * np.dot(hidden_outputs.T, error) / n_records
        
        # grad of hidden layer
        # (N, H) =  (N, C) dot (H, C).T
        dHiddenInputs = (np.dot(error, self.weights_hidden_to_output.T) / n_records) * hidden_outputs * (1 - hidden_outputs)
        # (D, H)
        self.weights_input_to_hidden += self.lr * np.dot(features.T, dHiddenInputs)
        
        
    def train_iterative(self, features, targets):
        ''' Train the network on batch of features and targets. 
        
            Arguments
            ---------
            
            features: 2D array, each row is one data record, each column is a feature
            targets: 1D array of target values
        
        '''
        # features (N, D)
        n_records = features.shape[0]

        # W1 (D, H)
        delta_weights_i_h = np.zeros(self.weights_input_to_hidden.shape)
        # W2 (H, C)
        delta_weights_h_o = np.zeros(self.weights_hidden_to_output.shape)
        for X, y in zip(features, targets):
            #### Implement the forward pass here ####
            ### Forward pass ###
            # TODO: Hidden layer - Replace these values with your calculations.
            # (1, H) = (1, D) * (D, H)
            hidden_inputs = np.dot(X, self.weights_input_to_hidden) # signals into hidden layer
            hidden_outputs = self.activation_function(hidden_inputs) # signals from hidden layer

            # TODO: Output layer - Replace these values with your calculations.
            final_inputs = np.dot(hidden_outputs, self.weights_hidden_to_output) # signals into final output layer
            final_outputs = final_inputs # signals from final output layer

            #### Implement the backward pass here ####
            ### Backward pass ###

            # TODO: Output error - Replace this value with your calculations.
            # (C,)
            error = y - final_outputs # Output layer error is the difference between desired target and actual output.
            output_error_term = error       # df/dx = 1 - the contribution is 1 * error because we do the average later

            # TODO: Backpropagated error terms - Replace these values with your calculations.
            # (H, 1) = (H, C) dot (C,)
            hidden_error = np.dot(self.weights_hidden_to_output, output_error_term)
            # (1, 1)  = (1, H) dot (H, 1)
            hidden_error_term = hidden_outputs * (1 - hidden_outputs)* hidden_error

            # Weight step (input to hidden)
            
            # (D, H) += (1, 1) * (1, D)
            delta_weights_i_h += hidden_error_term * X[:, None]

            # Weight step (hidden to output)
            # (H, C) += (C, ) * (H, )
            delta_weights_h_o += output_error_term * hidden_outputs[:, None]

        # TODO: Update the weights - Replace these values with your calculations.
        self.weights_hidden_to_output += self.lr * delta_weights_h_o / n_records # update hidden-to-output weights with gradient descent step
        self.weights_input_to_hidden += self.lr * delta_weights_i_h / n_records # update input-to-hidden weights with gradient descent step

 
    def run(self, features):
        ''' Run a forward pass through the network with input features 
        
            Arguments
            ---------
            features: 1D array of feature values
        '''
        
        #### Implement the forward pass here ####
        # TODO: Hidden layer - replace these values with the appropriate calculations.
        hidden_inputs = np.dot(features, self.weights_input_to_hidden) # signals into hidden layer
        hidden_outputs = self.activation_function(hidden_inputs) # signals from hidden layer
        
        # TODO: Output layer - Replace these values with the appropriate calculations.
        final_inputs = np.dot(hidden_outputs, self.weights_hidden_to_output) # signals into final output layer
        final_outputs = final_inputs # signals from final output layer 
        
        return final_outputs

In [42]:
def MSE(y, Y):
    return np.mean((y-Y)**2)

Unit tests

Run these unit tests to check the correctness of your network implementation. This will help you be sure your network was implemented correctly befor you starting trying to train it. These tests must all be successful to pass the project.


In [43]:
import unittest

inputs = np.array([[0.5, -0.2, 0.1]])
targets = np.array([[0.4]])
test_w_i_h = np.array([[0.1, -0.2],
                       [0.4, 0.5],
                       [-0.3, 0.2]])
test_w_h_o = np.array([[0.3],
                       [-0.1]])

class TestMethods(unittest.TestCase):
    
    ##########
    # Unit tests for data loading
    ##########
    
    def test_data_path(self):
        # Test that file path to dataset has been unaltered
        self.assertTrue(data_path.lower() == 'bike-sharing-dataset/hour.csv')
        
    def test_data_loaded(self):
        # Test that data frame loaded
        self.assertTrue(isinstance(rides, pd.DataFrame))
    
    ##########
    # Unit tests for network functionality
    ##########

    def test_activation(self):
        network = NeuralNetwork(3, 2, 1, 0.5)
        # Test that the activation function is a sigmoid
        self.assertTrue(np.all(network.activation_function(0.5) == 1/(1+np.exp(-0.5))))

    def test_train(self):
        # Test that weights are updated correctly on training
        network = NeuralNetwork(3, 2, 1, 0.5)
        network.weights_input_to_hidden = test_w_i_h.copy()
        network.weights_hidden_to_output = test_w_h_o.copy()
        
        network.train(inputs, targets)
        
        self.assertTrue(np.allclose(network.weights_hidden_to_output, 
                                    np.array([[ 0.37275328], 
                                              [-0.03172939]])))

        self.assertTrue(np.allclose(network.weights_input_to_hidden,
                                    np.array([[ 0.10562014, -0.20185996], 
                                              [0.39775194, 0.50074398], 
                                              [-0.29887597, 0.19962801]])))

    def test_run(self):
        # Test correctness of run method
        network = NeuralNetwork(3, 2, 1, 0.5)
        network.weights_input_to_hidden = test_w_i_h.copy()
        network.weights_hidden_to_output = test_w_h_o.copy()

        self.assertTrue(np.allclose(network.run(inputs), 0.09998924))

suite = unittest.TestLoader().loadTestsFromModule(TestMethods())
unittest.TextTestRunner().run(suite)


.....
----------------------------------------------------------------------
Ran 5 tests in 0.007s

OK
Out[43]:
<unittest.runner.TextTestResult run=5 errors=0 failures=0>

Training the network

Here you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training set and will fail to generalize to the validation set. That is, the loss on the validation set will start increasing as the training set loss drops.

You'll also be using a method know as Stochastic Gradient Descent (SGD) to train the network. The idea is that for each training pass, you grab a random sample of the data instead of using the whole data set. You use many more training passes than with normal gradient descent, but each pass is much faster. This ends up training the network more efficiently. You'll learn more about SGD later.

Choose the number of iterations

This is the number of batches of samples from the training data we'll use to train the network. The more iterations you use, the better the model will fit the data. However, if you use too many iterations, then the model with not generalize well to other data, this is called overfitting. You want to find a number here where the network has a low training loss, and the validation loss is at a minimum. As you start overfitting, you'll see the training loss continue to decrease while the validation loss starts to increase.

Choose the learning rate

This scales the size of weight updates. If this is too big, the weights tend to explode and the network fails to fit the data. A good choice to start at is 0.1. If the network has problems fitting the data, try reducing the learning rate. Note that the lower the learning rate, the smaller the steps are in the weight updates and the longer it takes for the neural network to converge.

Choose the number of hidden nodes

The more hidden nodes you have, the more accurate predictions the model will make. Try a few different numbers and see how it affects the performance. You can look at the losses dictionary for a metric of the network performance. If the number of hidden units is too low, then the model won't have enough space to learn and if it is too high there are too many options for the direction that the learning can take. The trick here is to find the right balance in number of hidden units you choose.


In [51]:
## http://www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf
## random search for hyperparameter

import sys
import pandas as pd

models = []
for trial in range(20):
    ## perform random learning rate search 
    l = 10 ** np.random.uniform(-1, 0)
    
    nodes = int(10 ** np.random.uniform(1, 2))

    ### Set the hyperparameters here ###
    iterations = 10000
    learning_rate = l
    hidden_nodes = nodes
    output_nodes = 1

    N_i = train_features.shape[1]
    network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)

    losses = {'train':[], 'validation':[]}
    for ii in range(iterations):
        # Go through a random batch of 128 records from the training data set
        batch = np.random.choice(train_features.index, size=128)
        X, y = train_features.ix[batch].values, train_targets.ix[batch]['cnt']
        network.train(X, np.array(y)[:, None])

        # Printing out the training progress
        train_loss = MSE(network.run(train_features).T, train_targets['cnt'].values)
        val_loss = MSE(network.run(val_features).T, val_targets['cnt'].values)
        line = "\r"+str(trial)+" Progress: {:2.1f}".format(100 * ii/float(iterations)) \
                         + "% ... Training loss: " + str(train_loss)[:5] \
                         + " ... Validation loss: " + str(val_loss)[:5] \
                         + " l: " + str(l) \
                         + " nodes: " + str(nodes)
        sys.stdout.write(line)
        sys.stdout.flush()

        losses['train'].append(train_loss)
        losses['validation'].append(val_loss)
        

    latest = {"network": network, "losses": losses, "train": train_loss, "validation": val_loss, "learning_rate": l, "hidden_nodes": hidden_nodes}
    print(line)
    models.append(latest)


0 Progress: 100.0% ... Training loss: 0.054 ... Validation loss: 0.150 l: 0.3428875050587184 nodes: 25
1 Progress: 100.0% ... Training loss: 0.138 ... Validation loss: 0.260 l: 0.15341316395284513 nodes: 24
2 Progress: 100.0% ... Training loss: 0.053 ... Validation loss: 0.152 l: 0.814256536797731 nodes: 11
3 Progress: 100.0% ... Training loss: 0.277 ... Validation loss: 0.431 l: 0.1012484151412937 nodes: 58
4 Progress: 0.1% ... Training loss: 24208 ... Validation loss: 87114 l: 0.869365488273241 nodes: 59
/Users/sidazhang/miniconda2/envs/dlnd/lib/python3.6/site-packages/ipykernel_launcher.py:24: RuntimeWarning: overflow encountered in exp
4 Progress: 2.4% ... Training loss: nan ... Validation loss: nan l: 0.869365488273241 nodes: 59
/Users/sidazhang/miniconda2/envs/dlnd/lib/python3.6/site-packages/ipykernel_launcher.py:2: RuntimeWarning: overflow encountered in square
  
/Users/sidazhang/miniconda2/envs/dlnd/lib/python3.6/site-packages/ipykernel_launcher.py:111: RuntimeWarning: invalid value encountered in multiply
4 Progress: 100.0% ... Training loss: nan ... Validation loss: nan l: 0.869365488273241 nodes: 59
5 Progress: 100.0% ... Training loss: 0.067 ... Validation loss: 0.161 l: 0.3125471068835278 nodes: 54
6 Progress: 100.0% ... Training loss: 0.974 ... Validation loss: 1.367 l: 0.776001136833667 nodes: 57
7 Progress: 100.0% ... Training loss: 0.071 ... Validation loss: 0.155 l: 0.18151232953701749 nodes: 11
8 Progress: 100.0% ... Training loss: 0.957 ... Validation loss: 1.363 l: 0.978620682101072 nodes: 86
9 Progress: 100.0% ... Training loss: 0.064 ... Validation loss: 0.161 l: 0.2722278024010349 nodes: 10
10 Progress: 100.0% ... Training loss: 0.067 ... Validation loss: 0.221 l: 0.5791538042521548 nodes: 10
11 Progress: 100.0% ... Training loss: 0.056 ... Validation loss: 0.155 l: 0.566011405254768 nodes: 19
12 Progress: 100.0% ... Training loss: 0.184 ... Validation loss: 0.327 l: 0.10155634219872826 nodes: 13
13 Progress: 100.0% ... Training loss: 0.152 ... Validation loss: 0.285 l: 0.146416208662602 nodes: 54
14 Progress: 100.0% ... Training loss: 0.882 ... Validation loss: 1.372 l: 0.24067056429554703 nodes: 98
15 Progress: 100.0% ... Training loss: 0.052 ... Validation loss: 0.132 l: 0.7759936514209134 nodes: 20
16 Progress: 100.0% ... Training loss: 0.107 ... Validation loss: 0.211 l: 0.13813909005477734 nodes: 18
17 Progress: 100.0% ... Training loss: 0.084 ... Validation loss: 0.196 l: 0.15778306182834342 nodes: 37
18 Progress: 100.0% ... Training loss: 0.539 ... Validation loss: 0.984 l: 0.38767207588746294 nodes: 97
19 Progress: 100.0% ... Training loss: 0.059 ... Validation loss: 0.138 l: 0.9035979148124579 nodes: 11

In [52]:
import pandas as pd
df = pd.DataFrame(models)

In [53]:
## http://www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf
## random search for hyperparameter yields the best model at 14 nodes and l of 0.81

df.sort_values("validation")


Out[53]:
hidden_nodes learning_rate losses network train validation
15 20 0.775994 {'train': [10.1949809663, 65.9996528706, 45.24... <__main__.NeuralNetwork object at 0x118a5f278> 0.052990 0.132826
19 11 0.903598 {'train': [0.98871905539, 0.974692227664, 0.97... <__main__.NeuralNetwork object at 0x1192fa8d0> 0.059355 0.138743
0 25 0.342888 {'train': [1.07581527317, 1.61068792352, 1.668... <__main__.NeuralNetwork object at 0x1192df710> 0.054413 0.150363
2 11 0.814257 {'train': [1.75763185471, 2.07756246069, 3.167... <__main__.NeuralNetwork object at 0x11b3780f0> 0.053150 0.152337
7 11 0.181512 {'train': [0.999637659792, 0.993102129773, 0.9... <__main__.NeuralNetwork object at 0x11451d860> 0.071682 0.155132
11 19 0.566011 {'train': [1.08385842684, 1.10239246266, 1.493... <__main__.NeuralNetwork object at 0x112793828> 0.056792 0.155595
5 54 0.312547 {'train': [3.72957838471, 32.1114977081, 285.9... <__main__.NeuralNetwork object at 0x11432e710> 0.067762 0.161827
9 10 0.272228 {'train': [0.947496939953, 0.934147697753, 0.9... <__main__.NeuralNetwork object at 0x118a58cc0> 0.064109 0.161918
17 37 0.157783 {'train': [1.03139652695, 1.09683475474, 0.953... <__main__.NeuralNetwork object at 0x11432ec50> 0.084877 0.196203
16 18 0.138139 {'train': [0.986764568999, 0.993550299352, 0.9... <__main__.NeuralNetwork object at 0x112793c50> 0.107457 0.211792
10 10 0.579154 {'train': [1.04469614237, 0.872261450345, 0.83... <__main__.NeuralNetwork object at 0x118a58ef0> 0.067545 0.221487
1 24 0.153413 {'train': [0.959336155334, 0.979008815122, 0.9... <__main__.NeuralNetwork object at 0x118a58160> 0.138336 0.260288
13 54 0.146416 {'train': [0.935139860914, 0.927401364724, 0.9... <__main__.NeuralNetwork object at 0x1143cbe48> 0.152452 0.285727
12 13 0.101556 {'train': [1.12009336608, 1.04775690563, 1.020... <__main__.NeuralNetwork object at 0x118a5fc18> 0.184115 0.327619
3 58 0.101248 {'train': [1.52257230144, 1.04817634632, 1.062... <__main__.NeuralNetwork object at 0x118a5fcf8> 0.277727 0.431155
18 97 0.387672 {'train': [13.8393250495, 903.785975195, 4955.... <__main__.NeuralNetwork object at 0x118a58780> 0.539430 0.984976
8 86 0.978621 {'train': [1.11594240985, 199.151116075, 20231... <__main__.NeuralNetwork object at 0x118a5f4e0> 0.957930 1.363191
6 57 0.776001 {'train': [67.1666357811, 3568.31603386, 7.718... <__main__.NeuralNetwork object at 0x118a58668> 0.974566 1.367593
14 98 0.240671 {'train': [6.88680371012, 147.634800414, 2920.... <__main__.NeuralNetwork object at 0x112793da0> 0.882267 1.372751
4 59 0.869365 {'train': [7.60486505359, 875.635142406, 357.5... <__main__.NeuralNetwork object at 0x1154e6dd8> NaN NaN

The best model was:

learning rate of 0.775994 and hidden nodes of 20

However, the models with low hidden nodes and a range of learning rate all had similarly good validation performance

This is done through log scale, random hyperparameter search

http://www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf


In [62]:
plt.scatter(df['learning_rate'], df['hidden_nodes'], marker='o', c='b', s=df['validation'] * 100, label='Validation Loss')
plt.xlabel('learning_rate')
plt.ylabel('hidden_nodes')


Out[62]:
<matplotlib.text.Text at 0x1150fbb38>

In [63]:
best_model = df.sort_values("validation").iloc[0]

plt.plot(best_model['losses']['train'], label='Training loss')
plt.plot(best_model['losses']['validation'], label='Validation loss')
plt.legend()
_ = plt.ylim(0.0, 1)


Check out your predictions

Here, use the test data to view how well your network is modeling the data. If something is completely wrong here, make sure each step in your network is implemented correctly.


In [64]:
network = best_model['network']
fig, ax = plt.subplots(figsize=(8,4))

mean, std = scaled_features['cnt']
predictions = network.run(test_features).T*std + mean
ax.plot(predictions[0], label='Prediction')
ax.plot((test_targets['cnt']*std + mean).values, label='Data')
ax.set_xlim(right=len(predictions))
ax.legend()

dates = pd.to_datetime(rides.ix[test_data.index]['dteday'])
dates = dates.apply(lambda d: d.strftime('%b %d'))
ax.set_xticks(np.arange(len(dates))[12::24])
_ = ax.set_xticklabels(dates[12::24], rotation=45)


OPTIONAL: Thinking about your results(this question will not be evaluated in the rubric).

Answer these questions about your results. How well does the model predict the data? Where does it fail? Why does it fail where it does?

Note: You can edit the text in this cell by double clicking on it. When you want to render the text, press control + enter

It fails around Christmas which is a holiday period and the model has not seen holiday data and so the predictive power of the model is weak around this time

Your answer below


In [ ]: