📑   P1: 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 [510]:
%%html
<style>
@import url('https://fonts.googleapis.com/css?family=Orbitron');
body {background-color: oldlace;}
a {color: firebrick; font-family: Orbitron;}
h1, h2 {color: #ff603b; font-family: Orbitron; text-shadow: 4px 4px 4px #aaa;}
h3, h4 {color: firebrick; font-family: Orbitron; text-shadow: 4px 4px 4px #aaa;}
</style>
<script>
code_show = true; 
function code_display() {
    if (code_show) {
        $('div.input').each(function(id) {
            if (id == 0 || $(this).html().indexOf('hide_code') > -1) {$(this).hide();}
        });
        $('div.output_prompt').css('opacity', 0);
    } else {
        $('div.input').each(function(id) {$(this).show();});
        $('div.output_prompt').css('opacity', 1);
    };
    code_show = !code_show;
} 
$(document).ready(code_display);
</script>
<form action="javascript: code_display()">
<input style="color: #ff603b; background: oldlace; opacity: 0.8;" \ 
type="submit" value="Click to display or hide code cells">
</form>
In [376]:
hide_code=''
import numpy as np
import pandas as pd
from scipy.special import expit

import unittest
import sys

from matplotlib import rcParams
import matplotlib.pyplot as plt

%matplotlib inline
%config InlineBackend.figure_format = 'retina'

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 [377]:
hide_code
data_path = 'Bike-Sharing-Dataset/hour.csv'

rides = pd.read_csv(data_path)
rides[:10].T[:15]
Out[377]:
0 1 2 3 4 5 6 7 8 9
instant 1 2 3 4 5 6 7 8 9 10
dteday 2011-01-01 2011-01-01 2011-01-01 2011-01-01 2011-01-01 2011-01-01 2011-01-01 2011-01-01 2011-01-01 2011-01-01
season 1 1 1 1 1 1 1 1 1 1
yr 0 0 0 0 0 0 0 0 0 0
mnth 1 1 1 1 1 1 1 1 1 1
hr 0 1 2 3 4 5 6 7 8 9
holiday 0 0 0 0 0 0 0 0 0 0
weekday 6 6 6 6 6 6 6 6 6 6
workingday 0 0 0 0 0 0 0 0 0 0
weathersit 1 1 1 1 1 2 1 1 1 1
temp 0.24 0.22 0.22 0.24 0.24 0.24 0.22 0.2 0.24 0.32
atemp 0.2879 0.2727 0.2727 0.2879 0.2879 0.2576 0.2727 0.2576 0.2879 0.3485
hum 0.81 0.8 0.8 0.75 0.75 0.75 0.8 0.86 0.75 0.76
windspeed 0 0 0 0 0 0.0896 0 0 0 0
casual 3 8 5 3 0 0 2 1 1 8

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 [378]:
hide_code
plt.style.use('seaborn-whitegrid')
rcParams['figure.figsize'] = (18, 6)
rides[:24*10].plot(x='dteday', y='cnt', color='#ff603b');

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 [379]:
hide_code
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[:15].T[:10]
Out[379]:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
yr 0.00 0.00 0.00 0.00 0.00 0.0000 0.00 0.00 0.00 0.00 0.0000 0.0000 0.0000 0.0000 0.0000
holiday 0.00 0.00 0.00 0.00 0.00 0.0000 0.00 0.00 0.00 0.00 0.0000 0.0000 0.0000 0.0000 0.0000
temp 0.24 0.22 0.22 0.24 0.24 0.2400 0.22 0.20 0.24 0.32 0.3800 0.3600 0.4200 0.4600 0.4600
hum 0.81 0.80 0.80 0.75 0.75 0.7500 0.80 0.86 0.75 0.76 0.7600 0.8100 0.7700 0.7200 0.7200
windspeed 0.00 0.00 0.00 0.00 0.00 0.0896 0.00 0.00 0.00 0.00 0.2537 0.2836 0.2836 0.2985 0.2836
casual 3.00 8.00 5.00 3.00 0.00 0.0000 2.00 1.00 1.00 8.00 12.0000 26.0000 29.0000 47.0000 35.0000
registered 13.00 32.00 27.00 10.00 1.00 1.0000 0.00 2.00 7.00 6.00 24.0000 30.0000 55.0000 47.0000 71.0000
cnt 16.00 40.00 32.00 13.00 1.00 1.0000 2.00 3.00 8.00 14.00 36.0000 56.0000 84.0000 94.0000 106.0000
season_1 1.00 1.00 1.00 1.00 1.00 1.0000 1.00 1.00 1.00 1.00 1.0000 1.0000 1.0000 1.0000 1.0000
season_2 0.00 0.00 0.00 0.00 0.00 0.0000 0.00 0.00 0.00 0.00 0.0000 0.0000 0.0000 0.0000 0.0000

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 [380]:
hide_code
quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed']

# Store scalings in a dictionary so we can convert back later
scaled_features = {}

scaled_data = data.copy()

for each in quant_features:
    mean, std = data[each].mean(), data[each].std()
    scaled_features[each] = [mean, std]
    scaled_data[each] = (data[each] - mean)/std

scaled_data[:10].T[:10]
Out[380]:
0 1 2 3 4 5 6 7 8 9
yr 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
holiday 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
temp -1.334609 -1.438475 -1.438475 -1.334609 -1.334609 -1.334609 -1.438475 -1.542341 -1.334609 -0.919146
hum 0.947345 0.895513 0.895513 0.636351 0.636351 0.636351 0.895513 1.206507 0.636351 0.688184
windspeed -1.553844 -1.553844 -1.553844 -1.553844 -1.553844 -0.821460 -1.553844 -1.553844 -1.553844 -1.553844
casual -0.662736 -0.561326 -0.622172 -0.662736 -0.723582 -0.723582 -0.683018 -0.703300 -0.703300 -0.561326
registered -0.930162 -0.804632 -0.837666 -0.949983 -1.009445 -1.009445 -1.016052 -1.002838 -0.969804 -0.976411
cnt -0.956312 -0.823998 -0.868103 -0.972851 -1.039008 -1.039008 -1.033495 -1.027981 -1.000416 -0.967338
season_1 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000
season_2 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
In [382]:
scaled_features
Out[382]:
{'casual': [35.676218424535357, 49.30503038705308],
 'cnt': [189.46308763450142, 181.38759909186473],
 'hum': [0.6272288394038783, 0.19292983406291508],
 'registered': [153.78686920996606, 151.35728591258314],
 'temp': [0.4969871684216583, 0.19255612124972191],
 'windspeed': [0.1900976063064618, 0.12234022857279049]}

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 [383]:
hide_code
# Save data for approximately the last 21 days 
test_data = scaled_data[-21*24:]

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

# Separate the data into features and targets
target_fields = ['cnt', 'casual', 'registered']
features, targets = scaled_data.drop(target_fields, axis=1), scaled_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 [384]:
hide_code
# 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:]
train_features.shape, train_targets.shape, val_features.shape, val_targets.shape
Out[384]:
((15435, 56), (15435, 3), (1440, 56), (1440, 3))

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.

<img src="assets/neural_network.png" width=300px>

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 [385]:
hide_code
class NeuralNetwork(object):
    def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
        # Set number of nodes in input, hidden and output layers.
        self.input_nodes = input_nodes
        self.hidden_nodes = hidden_nodes
        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.learning_rate = 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.
 
        # Replace 0 with your sigmoid calculation
        # expit(x) == 1.0 / (1.0 + np.exp(-x)) || imported from scipy.special
        self.activation_function = lambda x : expit(x) 
        self.activation_function_gradient = lambda z : z * (1 - z)
        
        ### 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):
        # Replace 0 with your sigmoid calculation here
        #    return 1.0/(1.0 + np.exp(-x))  
        # self.activation_function = sigmoid
                    
    def train(self, features, targets):
        ''' Train the net work 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
        
        '''
        n_records = features.shape[0]
        delta_weights_i_h = np.zeros(self.weights_input_to_hidden.shape)
        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.
            
            # signals into hidden layer
            hidden_inputs = X.dot(self.weights_input_to_hidden)
            # signals from hidden layer
            hidden_outputs = self.activation_function(hidden_inputs)

            # TODO: Output layer - Replace these values with your calculations.
        
            # signals into final output layer
            final_inputs = hidden_outputs.dot(self.weights_hidden_to_output)            
            # signals from final output layer
            final_outputs = final_inputs
            
            #### Implement the backward pass here ####
            ### Backward pass ###

            # TODO: Output errort, hidden layer's error - Replace these values with your calculations.
            
            # Output layer error is the difference between desired target and actual output.
            errors = y - final_outputs
            
            # Calculate the hidden layer's contribution to the error
            hidden_errors = self.weights_hidden_to_output.dot(errors)
            
            # TODO: Backpropagated error terms - Replace these values with your calculations.
            output_error_terms = errors * 1.0
            hidden_error_terms = hidden_errors * self.activation_function_gradient(hidden_outputs)

            # Weight step (input to hidden)
            delta_weights_i_h += hidden_error_terms * X [:, None]
            # Weight step (hidden to output)
            delta_weights_h_o += output_error_terms * hidden_outputs[:, None]
        
        # TODO: Update the weights - Replace these values with your calculations.
        
        # update input-to-hidden weights with gradient descent step
        self.weights_input_to_hidden += self.learning_rate * delta_weights_i_h / n_records 
        # update hidden-to-output weights with gradient descent step
        self.weights_hidden_to_output += self.learning_rate * delta_weights_h_o / n_records 

    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.
        
        # signals into hidden layer
        hidden_inputs = features.dot(self.weights_input_to_hidden)
        # signals from hidden layer
        hidden_outputs = self.activation_function(hidden_inputs) 
        
        # TODO: Output layer - Replace these values with the appropriate calculations.
        
        # signals into final output layer
        final_inputs = hidden_outputs.dot(self.weights_hidden_to_output)
        # signals from final output layer
        final_outputs = final_inputs * 1.0
        
        return final_outputs
In [386]:
hide_code
def MSE(y, Y):
    return np.mean(np.array((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 [387]:
hide_code
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.061s

OK
Out[387]:
<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. Normally a good choice to start at is 0.1; however, if you effectively divide the learning rate by n_records, try starting out with a learning rate of 1. In either case, 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 [507]:
hide_code
### Set the hyperparameters here ###
iterations = 4000
learning_rate = 0.5
hidden_nodes = 28
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.iloc[batch].values, train_targets.iloc[batch]['cnt']
                             
    network.train(X, y)
    
    # 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)
    sys.stdout.write("\rProgress: {:2.1f}".format(100 * ii/float(iterations)) + \
                     "% ... Training loss: " + str(train_loss)[:5] + 
                     " ... Validation loss: " + str(val_loss)[:5])
    sys.stdout.flush()
    
    losses['train'].append(train_loss)
    losses['validation'].append(val_loss)
Progress: 100.0% ... Training loss: 0.066 ... Validation loss: 0.147
In [512]:
hide_code

plt.plot(losses['train'][100:], label='Training loss')
plt.plot(losses['validation'][100:], color='#ff603b', label='Validation loss')
plt.legend()
_ = plt.ylim()

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 [505]:
hide_code
mean, std = scaled_features['cnt']
predictions = network.run(test_features).T*std + mean
In [514]:
hide_code
fig, ax = plt.subplots(figsize=(18,9))

ax.plot(np.array(predictions)[0], label='Prediction')
ax.plot((test_targets['cnt']*std + mean).values, color='#ff603b', label='Data')
ax.set_xlim(right=np.array(predictions).shape[1])
ax.legend()

dates = pd.to_datetime(rides.iloc[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

Your answer below

The predictions look very close to the real data for the first 20 days (11th - 20th of December), but the model was failing after the 21st (especially 21st - 26th of December). I think the reason is that the rentals could decrease during the Christmas holidays and the model did not have enough features to catch the seasonal tendencies so it cannot predict this period correctly. Further increase in iterations will lead to overfitting, but will not improve the accuracy of the forecasts.