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

rides = pd.read_csv(data_path)

In [52]:
rides.head()


Out[52]:
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

In [53]:
rides.tail()


Out[53]:
instant dteday season yr mnth hr holiday weekday workingday weathersit temp atemp hum windspeed casual registered cnt
17374 17375 2012-12-31 1 1 12 19 0 1 1 2 0.26 0.2576 0.60 0.1642 11 108 119
17375 17376 2012-12-31 1 1 12 20 0 1 1 2 0.26 0.2576 0.60 0.1642 8 81 89
17376 17377 2012-12-31 1 1 12 21 0 1 1 1 0.26 0.2576 0.60 0.1642 7 83 90
17377 17378 2012-12-31 1 1 12 22 0 1 1 1 0.26 0.2727 0.56 0.1343 13 48 61
17378 17379 2012-12-31 1 1 12 23 0 1 1 1 0.26 0.2727 0.65 0.1343 12 37 49

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 [54]:
rides[:24*10].plot(x='dteday', y='cnt')


Out[54]:
<matplotlib.axes._subplots.AxesSubplot at 0x10dea9208>

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 [55]:
#create dummy variables for categorical data
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)
#axis = 1 ? 
data.head()


Out[55]:
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 [56]:
quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed']
# Store scalings  
scaled_features = {}
for each in quant_features:
    mean, std = data[each].mean(), data[each].std()
    print('mean:', mean)
    print('std:', std)
    print('each:', each)
   # print(loc)
    scaled_features[each] = [mean, std]
    #x = np.data
    #trying to take a look at the matrix index size [:,each]
    #need to somehow access .shape of matrix not sure how?
    data.loc[:, each] = (data[each] - mean)/std


mean: 35.67621842453536
std: 49.305030387053186
each: casual
mean: 153.78686920996606
std: 151.35728591258317
each: registered
mean: 189.46308763450142
std: 181.38759909186527
each: cnt
mean: 0.4969871684216586
std: 0.19255612124972407
each: temp
mean: 0.6272288394038822
std: 0.1929298340629125
each: hum
mean: 0.1900976063064631
std: 0.12234022857279413
each: windspeed

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 [57]:
# Save data for approximately the last 21 days 
test_data = data[-21*24:]
#print(test_data)

# Now remove the test data from the data set because
# we don't want to train our data on our test set!
#how do i know whats the test data set? 
data = data[:-21*24]
print(data)
# Separate the data into features and targets
#drop all of the target_fields from data & test_data
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]


       yr  holiday      temp       hum  windspeed    casual  registered  \
0       0        0 -1.334609  0.947345  -1.553844 -0.662736   -0.930162   
1       0        0 -1.438475  0.895513  -1.553844 -0.561326   -0.804632   
2       0        0 -1.438475  0.895513  -1.553844 -0.622172   -0.837666   
3       0        0 -1.334609  0.636351  -1.553844 -0.662736   -0.949983   
4       0        0 -1.334609  0.636351  -1.553844 -0.723582   -1.009445   
5       0        0 -1.334609  0.636351  -0.821460 -0.723582   -1.009445   
6       0        0 -1.438475  0.895513  -1.553844 -0.683018   -1.016052   
7       0        0 -1.542341  1.206507  -1.553844 -0.703300   -1.002838   
8       0        0 -1.334609  0.636351  -1.553844 -0.703300   -0.969804   
9       0        0 -0.919146  0.688184  -1.553844 -0.561326   -0.976411   
10      0        0 -0.607548  0.688184   0.519881 -0.480199   -0.857487   
11      0        0 -0.711414  0.947345   0.764282 -0.196252   -0.817845   
12      0        0 -0.399817  0.740016   0.764282 -0.135406   -0.652673   
13      0        0 -0.192085  0.480854   0.886073  0.229668   -0.705528   
14      0        0 -0.192085  0.480854   0.764282 -0.013715   -0.546963   
15      0        0 -0.295951  0.740016   0.886073  0.087695   -0.553570   
16      0        0 -0.399817  0.999178   0.886073  0.107976   -0.672494   
17      0        0 -0.295951  0.999178   0.764282 -0.419353   -0.672494   
18      0        0 -0.399817  1.310171   0.519881 -0.541045   -0.844273   
19      0        0 -0.399817  1.310171   0.519881 -0.601890   -0.811239   
20      0        0 -0.503683  1.258339   0.519881 -0.500481   -0.850880   
21      0        0 -0.503683  1.258339   0.031898 -0.662736   -0.811239   
22      0        0 -0.503683  1.621165   0.276298 -0.500481   -0.903735   
23      0        0 -0.192085  1.310171   0.886073 -0.419353   -0.857487   
24      0        0 -0.192085  1.310171   0.886073 -0.642454   -0.930162   
25      0        0 -0.295951  1.621165   0.519881 -0.703300   -0.910342   
26      0        0 -0.399817  1.932159   0.764282 -0.703300   -0.963197   
27      0        0 -0.192085  1.621165   0.031898 -0.683018   -0.989624   
28      0        0 -0.192085  1.621165   0.031898 -0.683018   -1.009445   
29      0        0 -0.399817  0.740016   0.886073 -0.723582   -1.002838   
...    ..      ...       ...       ...        ...       ...         ...   
16845   1        0 -0.711414  1.569333  -0.211685 -0.054279    0.437462   
16846   1        0 -0.711414  1.569333  -0.456086 -0.317944    0.364787   
16847   1        0 -0.711414  1.569333  -0.821460 -0.378789    0.179794   
16848   1        0 -0.607548  1.621165  -0.821460 -0.480199   -0.289295   
16849   1        0 -0.711414  1.932159  -0.821460 -0.601890   -0.342150   
16850   1        0 -0.711414  1.932159  -0.699669 -0.520763   -0.447860   
16851   1        0 -0.711414  1.569333  -0.699669 -0.662736   -0.520536   
16852   1        0 -0.711414  1.932159  -0.821460 -0.662736   -0.698922   
16853   1        0 -0.711414  1.932159  -0.821460 -0.723582   -0.883914   
16854   1        0 -0.711414  1.932159  -1.553844 -0.723582   -0.989624   
16855   1        0 -0.607548  1.621165  -0.699669 -0.683018   -0.996231   
16856   1        0 -0.607548  1.621165  -0.699669 -0.723582   -0.989624   
16857   1        0 -0.607548  1.621165  -0.699669 -0.662736   -0.956590   
16858   1        0 -0.607548  1.621165  -0.699669 -0.723582   -0.837666   
16859   1        0 -0.607548  1.621165  -0.211685 -0.683018   -0.216619   
16860   1        0 -0.607548  1.621165   0.519881 -0.662736    0.906551   
16861   1        0 -0.399817  1.932159   0.519881 -0.541045    2.782906   
16862   1        0 -0.399817  1.932159   0.276298 -0.500481    0.787627   
16863   1        0 -0.295951  1.621165   0.276298 -0.480199   -0.216619   
16864   1        0 -0.192085  1.621165   0.276298 -0.561326   -0.183585   
16865   1        0 -0.295951  1.932159   0.276298 -0.257098   -0.025019   
16866   1        0 -0.295951  1.932159   0.276298 -0.115125    0.239256   
16867   1        0  0.015647  1.621165   0.276298 -0.094843    0.166580   
16868   1        0  0.015647  1.258339  -0.211685 -0.135406    0.351573   
16869   1        0  0.015647  1.310171  -0.699669  0.026849    1.018868   
16870   1        0 -0.088219  0.999178   0.764282  0.047131    2.802727   
16871   1        0 -0.192085  1.310171   0.764282 -0.317944    2.578093   
16872   1        0  0.119512  0.740016   0.764282 -0.358507    1.686163   
16873   1        0 -0.192085  1.310171   0.519881 -0.459917    0.880124   
16874   1        0 -0.192085  1.621165   0.031898 -0.297662    0.463890   

            cnt  season_1  season_2    ...      hr_21  hr_22  hr_23  \
0     -0.956312         1         0    ...          0      0      0   
1     -0.823998         1         0    ...          0      0      0   
2     -0.868103         1         0    ...          0      0      0   
3     -0.972851         1         0    ...          0      0      0   
4     -1.039008         1         0    ...          0      0      0   
5     -1.039008         1         0    ...          0      0      0   
6     -1.033495         1         0    ...          0      0      0   
7     -1.027981         1         0    ...          0      0      0   
8     -1.000416         1         0    ...          0      0      0   
9     -0.967338         1         0    ...          0      0      0   
10    -0.846051         1         0    ...          0      0      0   
11    -0.735789         1         0    ...          0      0      0   
12    -0.581424         1         0    ...          0      0      0   
13    -0.526293         1         0    ...          0      0      0   
14    -0.460137         1         0    ...          0      0      0   
15    -0.438084         1         0    ...          0      0      0   
16    -0.531806         1         0    ...          0      0      0   
17    -0.675146         1         0    ...          0      0      0   
18    -0.851564         1         0    ...          0      0      0   
19    -0.840538         1         0    ...          0      0      0   
20    -0.846051         1         0    ...          0      0      0   
21    -0.857077         1         0    ...          1      0      0   
22    -0.890155         1         0    ...          0      1      0   
23    -0.829511         1         0    ...          0      0      1   
24    -0.950799         1         0    ...          0      0      0   
25    -0.950799         1         0    ...          0      0      0   
26    -0.994903         1         0    ...          0      0      0   
27    -1.011442         1         0    ...          0      0      0   
28    -1.027981         1         0    ...          0      0      0   
29    -1.033495         1         0    ...          0      0      0   
...         ...       ...       ...    ...        ...    ...    ...   
16845  0.350283         0         0    ...          0      0      0   
16846  0.217969         0         0    ...          0      0      0   
16847  0.047064         0         0    ...          0      0      0   
16848 -0.371928         0         0    ...          0      0      0   
16849 -0.449111         0         0    ...          0      0      0   
16850 -0.515267         0         0    ...          1      0      0   
16851 -0.614502         0         0    ...          0      1      0   
16852 -0.763355         0         0    ...          0      0      1   
16853 -0.934260         0         0    ...          0      0      0   
16854 -1.022468         0         0    ...          0      0      0   
16855 -1.016955         0         0    ...          0      0      0   
16856 -1.022468         0         0    ...          0      0      0   
16857 -0.978364         0         0    ...          0      0      0   
16858 -0.895668         0         0    ...          0      0      0   
16859 -0.366415         0         0    ...          0      0      0   
16860  0.576318         0         0    ...          0      0      0   
16861  2.175104         0         0    ...          0      0      0   
16862  0.521187         0         0    ...          0      0      0   
16863 -0.311284         0         0    ...          0      0      0   
16864 -0.305771         0         0    ...          0      0      0   
16865 -0.090762         0         0    ...          0      0      0   
16866  0.168352         0         0    ...          0      0      0   
16867  0.113221         0         0    ...          0      0      0   
16868  0.256561         0         0    ...          0      0      0   
16869  0.857484         0         0    ...          0      0      0   
16870  2.351522         0         0    ...          0      0      0   
16871  2.064843         0         0    ...          0      0      0   
16872  1.309554         0         0    ...          0      0      0   
16873  0.609396         0         0    ...          0      0      0   
16874  0.306178         0         0    ...          1      0      0   

       weekday_0  weekday_1  weekday_2  weekday_3  weekday_4  weekday_5  \
0              0          0          0          0          0          0   
1              0          0          0          0          0          0   
2              0          0          0          0          0          0   
3              0          0          0          0          0          0   
4              0          0          0          0          0          0   
5              0          0          0          0          0          0   
6              0          0          0          0          0          0   
7              0          0          0          0          0          0   
8              0          0          0          0          0          0   
9              0          0          0          0          0          0   
10             0          0          0          0          0          0   
11             0          0          0          0          0          0   
12             0          0          0          0          0          0   
13             0          0          0          0          0          0   
14             0          0          0          0          0          0   
15             0          0          0          0          0          0   
16             0          0          0          0          0          0   
17             0          0          0          0          0          0   
18             0          0          0          0          0          0   
19             0          0          0          0          0          0   
20             0          0          0          0          0          0   
21             0          0          0          0          0          0   
22             0          0          0          0          0          0   
23             0          0          0          0          0          0   
24             1          0          0          0          0          0   
25             1          0          0          0          0          0   
26             1          0          0          0          0          0   
27             1          0          0          0          0          0   
28             1          0          0          0          0          0   
29             1          0          0          0          0          0   
...          ...        ...        ...        ...        ...        ...   
16845          1          0          0          0          0          0   
16846          1          0          0          0          0          0   
16847          1          0          0          0          0          0   
16848          1          0          0          0          0          0   
16849          1          0          0          0          0          0   
16850          1          0          0          0          0          0   
16851          1          0          0          0          0          0   
16852          1          0          0          0          0          0   
16853          0          1          0          0          0          0   
16854          0          1          0          0          0          0   
16855          0          1          0          0          0          0   
16856          0          1          0          0          0          0   
16857          0          1          0          0          0          0   
16858          0          1          0          0          0          0   
16859          0          1          0          0          0          0   
16860          0          1          0          0          0          0   
16861          0          1          0          0          0          0   
16862          0          1          0          0          0          0   
16863          0          1          0          0          0          0   
16864          0          1          0          0          0          0   
16865          0          1          0          0          0          0   
16866          0          1          0          0          0          0   
16867          0          1          0          0          0          0   
16868          0          1          0          0          0          0   
16869          0          1          0          0          0          0   
16870          0          1          0          0          0          0   
16871          0          1          0          0          0          0   
16872          0          1          0          0          0          0   
16873          0          1          0          0          0          0   
16874          0          1          0          0          0          0   

       weekday_6  
0              1  
1              1  
2              1  
3              1  
4              1  
5              1  
6              1  
7              1  
8              1  
9              1  
10             1  
11             1  
12             1  
13             1  
14             1  
15             1  
16             1  
17             1  
18             1  
19             1  
20             1  
21             1  
22             1  
23             1  
24             0  
25             0  
26             0  
27             0  
28             0  
29             0  
...          ...  
16845          0  
16846          0  
16847          0  
16848          0  
16849          0  
16850          0  
16851          0  
16852          0  
16853          0  
16854          0  
16855          0  
16856          0  
16857          0  
16858          0  
16859          0  
16860          0  
16861          0  
16862          0  
16863          0  
16864          0  
16865          0  
16866          0  
16867          0  
16868          0  
16869          0  
16870          0  
16871          0  
16872          0  
16873          0  
16874          0  

[16875 rows x 59 columns]

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 [58]:
# 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 [63]:
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.lr = learning_rate
        
        #### TODO **** 1.) : Set self.activation_function to your implemented sigmoid function ####
        #
        # Note: in Python, you can define a function with a lambda expression,
        # as shown below.
        #def sigmoid(x):
        self.activation_function = lambda x : 1.0 / (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 1 / (1+ np.exp(-x))
            #return 0  # Replace 0 with your sigmoid calculation here
        #    self.activation_function = lambda x : 1 / (1+np.exp(-x))
        #self.activation_function = sigmoid
        
                    
    
    def train(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
        
        '''
        n_records = features.shape[0]
        #are we supposed to zero the weights?????
        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):
            #### **** 2.) Implement the forward pass here ####
            ### Forward pass ###
            
            
            #list_target_y = np.array(y,ndmin = 2).T
            #np.array(X, ndmin = 2).T
            
            # TODO: Hidden layer - Replace these values with your calculations.
            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
            #final_outputs = self.activation_function(final_inputs) # signals from final output layer
            #### **** 3.) Implement the backward pass here ####
            ### Backward pass ###

            # TODO: Output error - Replace this value with your calculations.
            error = y - final_outputs # Output layer error is the difference between desired target and actual output.
            output_error_term = error * 1 #final_output*
            
            # TODO: Calculate the hidden layer's contribution to the error
            #hidden_error = np.dot(self.weights_hidden_to_output,output_error_term)
            
            # TODO: Backpropagated error terms - Replace these values with your calculations.
            hidden_error = np.dot(self.weights_hidden_to_output, error)
            hidden_error_term = hidden_error * hidden_outputs * (1 - hidden_outputs)

            #inputs_trans = inputs_X.T
            # Weight step (input to hidden)
            delta_weights_i_h += hidden_error_term * X[:,None] #update input to hidden w. grad descent
            # Weight step (hidden to output)
            delta_weights_h_o += output_error_term * hidden_outputs[:,None] #update hidden to output weigh w. grad descent
            
        # 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
        '''
        #inputs_features = np.array(features, ndmin =2).T
        
        #### **** 4.) Implement the forward pass here ####
        # TODO: Hidden layer - replace these values with the appropriate calculations.
        #ValueError: shapes (3,2) and (1,3) not aligned: 2 (dim 1) != 1 (dim 0) must change the shape
        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
       
        #print('shape', hidden_input.shape)
        # 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 [64]:
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 [65]:
import unittest
import numpy as np

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.011s

OK
Out[65]:
<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 [69]:
import sys

### Set the hyperparameters here ###
iterations = 6000
learning_rate = 0.6
hidden_nodes = 10
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, 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.058 ... Validation loss: 0.148

In [70]:
plt.plot(losses['train'], label='Training loss')
plt.plot(losses['validation'], 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 [71]:
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

Your answer below


In [ ]:


In [ ]:


In [ ]: