Planar Data Classification With One Hidden Layer v5
Planar Data Classification With One Hidden Layer v5
1 - Packages
Let's first import all the packages that you will need during this assignment.
numpy (www.numpy.org) is the fundamental package for scientific computing with Python.
sklearn (http://scikit-learn.org/stable/) provides simple and efficient tools for data mining and data
analysis.
matplotlib (http://matplotlib.org) is a library for plotting graphs in Python.
testCases provides some test examples to assess the correctness of your functions
planar_utils provide various useful functions used in this assignment
In [*]:
# Package imports
import numpy as np
import matplotlib.pyplot as plt
from testCases_v2 import *
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_d
%matplotlib inline
2 - Dataset
First, let's get the dataset you will work on. The following code will load a "flower" 2-class dataset into variables
X and Y.
In [*]:
X, Y = load_planar_dataset()
Visualize the dataset using matplotlib. The data looks like a "flower" with some red (label y=0) and some blue
(y=1) points. Your goal is to build a model to fit this data.
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20hi… 1/19
23/12/2018 Planar data classification with one hidden layer v5
In [*]:
You have:
Exercise: How many training examples do you have? In addition, what is the shape of the variables X and Y?
In [*]:
Expected Output:
shape of
(2, 400)
X
shape of
(1, 400)
Y
m 400
In [*]:
You can now plot the decision boundary of these models. Run the code below.
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20hi… 2/19
23/12/2018 Planar data classification with one hidden layer v5
In [*]:
# Print accuracy
LR_predictions = clf.predict(X.T)
print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-
'% ' + "(percentage of correctly labelled datapoints)")
Expected Output:
Accuracy 47%
Interpretation: The dataset is not linearly separable, so logistic regression doesn't perform well. Hopefully a
neural network will do better. Let's try this now!
Mathematically:
Given the predictions on all the examples, you can also compute the cost J as follows:
J = − m1 ∑ (y(i) log(a[2](i) ) +(1− y(i) )log(1− a[2](i) ))
m
(6)
i=0
Reminder: The general methodology to build a Neural Network is to:
You often build helper functions to compute steps 1-3 and then merge them into one function we call
nn_model(). Once you've built nn_model() and learnt the right parameters, you can make predictions on new
data.
Hint: Use shapes of X and Y to find n_x and n_y. Also, hard code the hidden layer size to be 4.
In [*]:
Returns:
n_x -- the size of the input layer
n_h -- the size of the hidden layer
n_y -- the size of the output layer
"""
### START CODE HERE ### (≈ 3 lines of code)
n_x = X.shape[0] # size of input layer
n_h = 4
n_y = Y.shape[0] # size of output layer
### END CODE HERE ###
return (n_x, n_h, n_y)
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20hi… 4/19
23/12/2018 Planar data classification with one hidden layer v5
In [*]:
Expected Output (these are not the sizes you will use for your network, they are just used to assess the
function you've just coded).
n_x 5
n_h 4
n_y 2
Instructions:
Make sure your parameters' sizes are right. Refer to the neural network figure above if needed.
You will initialize the weights matrices with random values.
Use: np.random.randn(a,b) * 0.01 to randomly initialize a matrix of shape (a,b).
You will initialize the bias vectors as zeros.
Use: np.zeros((a,b)) to initialize a matrix of shape (a,b) with zeros.
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20hi… 5/19
23/12/2018 Planar data classification with one hidden layer v5
In [*]:
Returns:
params -- python dictionary containing your parameters:
W1 -- weight matrix of shape (n_h, n_x)
b1 -- bias vector of shape (n_h, 1)
W2 -- weight matrix of shape (n_y, n_h)
b2 -- bias vector of shape (n_y, 1)
"""
np.random.seed(2) # we set up a seed so that your output matches ours although the init
return parameters
In [*]:
Expected Output:
b2 [[ 0.]]
Instructions:
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20hi… 7/19
23/12/2018 Planar data classification with one hidden layer v5
In [*]:
Returns:
A2 -- The sigmoid output of the second activation
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2"
"""
# Retrieve each parameter from the dictionary "parameters"
### START CODE HERE ### (≈ 4 lines of code)
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
### END CODE HERE ###
In [*]:
# Note: we use the mean here just to make sure that your output matches ours.
print(np.mean(cache['Z1']) ,np.mean(cache['A1']),np.mean(cache['Z2']),np.mean(cache['A2']))
Expected Output:
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20hi… 8/19
23/12/2018 Planar data classification with one hidden layer v5
There are many ways to implement the cross-entropy loss. To help you, we give you how we would
m
have implemented − i=0∑ y(i) log(a[2](i) ):
logprobs = np.multiply(np.log(A2),Y)
cost = - np.sum(logprobs) # no need to use a for loop!
(you can use either np.multiply() and then np.sum() or directly np.dot()).
In [*]:
Arguments:
A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
parameters -- python dictionary containing your parameters W1, b1, W2 and b2
Returns:
cost -- cross-entropy cost given equation (13)
"""
return cost
In [*]:
Expected Output:
cost 0.693058761...
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20hi… 9/19
23/12/2018 Planar data classification with one hidden layer v5
Using the cache computed during forward propagation, you can now implement backward propagation.
Instructions: Backpropagation is usually the hardest (most mathematical) part in deep learning. To help you,
here again is the slide from the lecture on backpropagation. You'll want to use the six equations on the right of
this slide, since you are building a vectorized implementation.
Tips:
To compute dZ1 you'll need to compute g[1]′ (Z [1] ). Since g[1] (.) is the tanh activation
function, if a = g[1] (z) then g[1] (z) = 1 − a2 . So you can compute g[1] (Z [1] ) using (1 -
′ ′
np.power(A1, 2)).
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20h… 10/19
23/12/2018 Planar data classification with one hidden layer v5
In [*]:
Arguments:
parameters -- python dictionary containing our parameters
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
X -- input data of shape (2, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
Returns:
grads -- python dictionary containing your gradients with respect to different paramete
"""
m = X.shape[1]
return grads
In [*]:
Expected output:
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20h… 11/19
23/12/2018 Planar data classification with one hidden layer v5
db2 [[-0.16655712]]
Question: Implement the update rule. Use gradient descent. You have to use (dW1, db1, dW2, db2) in order to
update (W1, b1, W2, b2).
General gradient descent rule: θ = θ − α ∂J∂θ where α is the learning rate and θ represents a parameter.
Illustration: The gradient descent algorithm with a good learning rate (converging) and a bad learning rate
(diverging). Images courtesy of Adam Harley.
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20h… 12/19
23/12/2018 Planar data classification with one hidden layer v5
In [*]:
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradients
Returns:
parameters -- python dictionary containing your updated parameters
"""
# Retrieve each parameter from the dictionary "parameters"
### START CODE HERE ### (≈ 4 lines of code)
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
### END CODE HERE ###
return parameters
In [*]:
Expected Output:
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20h… 13/19
23/12/2018 Planar data classification with one hidden layer v5
b2 [[ 0.00010457]]
Instructions: The neural network model has to use the previous functions in the right order.
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20h… 14/19
23/12/2018 Planar data classification with one hidden layer v5
In [*]:
Returns:
parameters -- parameters learnt by the model. They can then be used to predict.
"""
np.random.seed(3)
n_x = layer_sizes(X, Y)[0]
n_y = layer_sizes(X, Y)[2]
# Initialize parameters, then retrieve W1, b1, W2, b2. Inputs: "n_x, n_h, n_y". Outputs
### START CODE HERE ### (≈ 5 lines of code)
parameters = initialize_parameters(n_x, n_h, n_y)
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
### END CODE HERE ###
return parameters
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20h… 15/19
23/12/2018 Planar data classification with one hidden layer v5
In [*]:
Expected Output:
cost after
0.692739
iteration 0
⋮ ⋮
[[-0.65848169 1.21866811] [-0.76204273 1.39377573] [ 0.5792005 -1.10397703]
W1
[ 0.76773391 -1.41477129]]
b2 [[ 0.20459656]]
4.5 Predictions
Question: Use your model to predict by building predict(). Use forward propagation to predict results.
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20h… 16/19
23/12/2018 Planar data classification with one hidden layer v5
In [*]:
Arguments:
parameters -- python dictionary containing your parameters
X -- input data of size (n_x, m)
Returns
predictions -- vector of predictions of our model (red: 0 / blue: 1)
"""
# Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as
### START CODE HERE ### (≈ 2 lines of code)
A2, cache = forward_propagation(X, parameters)
predictions = np.round(A2)
### END CODE HERE ###
return predictions
In [*]:
Expected Output:
It is time to run the model and see how it performs on a planar dataset. Run the following code to test your
model with a single hidden layer of nh
hidden units.
In [*]:
Expected Output:
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20h… 17/19
23/12/2018 Planar data classification with one hidden layer v5
In [*]:
# Print accuracy
predictions = predict(parameters, X)
print ('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float
Expected Output:
Accuracy 90%
Accuracy is really high compared to Logistic Regression. The model has learnt the leaf patterns of the flower!
Neural networks are able to learn even highly non-linear decision boundaries, unlike logistic regression.
In [*]:
plt.figure(figsize=(16, 32))
hidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50]
for i, n_h in enumerate(hidden_layer_sizes):
plt.subplot(5, 2, i+1)
plt.title('Hidden Layer of size %d' % n_h)
parameters = nn_model(X, Y, n_h, num_iterations = 5000)
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
predictions = predict(parameters, X)
accuracy = float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*
print ("Accuracy for {} hidden units: {} %".format(n_h, accuracy))
Interpretation:
The larger models (with more hidden units) are able to fit the training set better, until eventually the
largest models overfit the data.
The best hidden layer size seems to be around n_h = 5. Indeed, a value around here seems to fits the
data well without also incurring noticable overfitting.
You will also learn later about regularization, which lets you use very large models (such as n_h = 50)
without much overfitting.
Optional questions:
Note: Remember to submit the assignment but clicking the blue "Submit Assignment" button at the upper-right.
What happens when you change the tanh activation for a sigmoid activation or a ReLU activation?
Play with the learning_rate. What happens?
What if we change the dataset? (See part 5 below!)
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20h… 18/19
23/12/2018 Planar data classification with one hidden layer v5
Nice work!
If you want, you can rerun the whole notebook (minus the dataset part) for each of the following datasets.
In [*]:
# Datasets
noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets()
X, Y = datasets[dataset]
X, Y = X.T, Y.reshape(1, Y.shape[0])
Reference:
http://scs.ryerson.ca/~aharley/neural-networks/ (http://scs.ryerson.ca/~aharley/neural-networks/)
http://cs231n.github.io/neural-networks-case-study/ (http://cs231n.github.io/neural-networks-case-
study/)
https://hub.coursera-notebooks.org/user/fwxnjaurublmkafifinzdh/notebooks/Week%203/Planar%20data%20classification%20with%20one%20h… 19/19