deeplearning.ai homework:Class 4 Week 2 Keras Tutorial Happy House
Keras tutorial - the Happy House
Welcome to the first assignment of week 2. In this assignment, you will:
- Learn to use Keras, a high-level neural networks API (programming framework), written in Python and capable of running on top of several lower-level frameworks including TensorFlow and CNTK.
- See how you can in a couple of hours build a deep learning algorithm.
Why are we using Keras? Keras was developed to enable deep learning engineers to build and experiment with different models very quickly. Just as TensorFlow is a higher-level framework than Python, Keras is an even higher-level framework and provides additional abstractions. Being able to go from idea to result with the least possible delay is key to finding good models. However, Keras is more restrictive than the lower-level frameworks, so there are some very complex models that you can implement in TensorFlow but not (without more difficulty) in Keras. That being said, Keras will work fine for many common models.
In this exercise, you’ll work on the “Happy House” problem, which we’ll explain below. Let’s load the required packages and solve the problem of the Happy House!
1 | import numpy as np |
Note: As you can see, we’ve imported a lot of functions from Keras. You can use them easily just by calling them directly in the notebook. Ex: X = Input(...)
or X = ZeroPadding2D(...)
.
1 - The Happy House
For your next vacation, you decided to spend a week with five of your friends from school. It is a very convenient house with many things to do nearby. But the most important benefit is that everybody has commited to be happy when they are in the house. So anyone wanting to enter the house must prove their current state of happiness.
As a deep learning expert, to make sure the “Happy” rule is strictly applied, you are going to build an algorithm which that uses pictures from the front door camera to check if the person is happy or not. The door should open only if the person is happy.
You have gathered pictures of your friends and yourself, taken by the front-door camera. The dataset is labbeled.
Run the following code to normalize the dataset and learn about its shapes.
1 | X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset() |
number of training examples = 600
number of test examples = 150
X_train shape: (600, 64, 64, 3)
Y_train shape: (600, 1)
X_test shape: (150, 64, 64, 3)
Y_test shape: (150, 1)
Details of the “Happy” dataset:
- Images are of shape (64,64,3)
- Training: 600 pictures
- Test: 150 pictures
It is now time to solve the “Happy” Challenge.
2 - Building a model in Keras
Keras is very good for rapid prototyping. In just a short time you will be able to build a model that achieves outstanding results.
Here is an example of a model in Keras:
1 | def model(input_shape): |
Note that Keras uses a different convention with variable names than we’ve previously used with numpy and TensorFlow. In particular, rather than creating and assigning a new variable on each step of forward propagation such as X
, Z1
, A1
, Z2
, A2
, etc. for the computations for the different layers, in Keras code each line above just reassigns X
to a new value using X = ...
. In other words, during each step of forward propagation, we are just writing the latest value in the commputation into the same variable X
. The only exception was X_input
, which we kept separate and did not overwrite, since we needed it at the end to create the Keras model instance (model = Model(inputs = X_input, ...)
above).
Exercise: Implement a HappyModel()
. This assignment is more open-ended than most. We suggest that you start by implementing a model using the architecture we suggest, and run through the rest of this assignment using that as your initial model. But after that, come back and take initiative to try out other model architectures. For example, you might take inspiration from the model above, but then vary the network architecture and hyperparameters however you wish. You can also use other functions such as AveragePooling2D()
, GlobalMaxPooling2D()
, Dropout()
.
Note: You have to be careful with your data’s shapes. Use what you’ve learned in the videos to make sure your convolutional, pooling and fully-connected layers are adapted to the volumes you’re applying it to.
1 | # GRADED FUNCTION: HappyModel |
You have now built a function to describe your model. To train and test this model, there are four steps in Keras:
- Create the model by calling the function above
- Compile the model by calling
model.compile(optimizer = "...", loss = "...", metrics = ["accuracy"])
- Train the model on train data by calling
model.fit(x = ..., y = ..., epochs = ..., batch_size = ...)
- Test the model on test data by calling
model.evaluate(x = ..., y = ...)
If you want to know more about model.compile()
, model.fit()
, model.evaluate()
and their arguments, refer to the official Keras documentation.
Exercise: Implement step 1, i.e. create the model.
1 | ### START CODE HERE ### (1 line) |
Exercise: Implement step 2, i.e. compile the model to configure the learning process. Choose the 3 arguments of compile()
wisely. Hint: the Happy Challenge is a binary classification problem.
1 | ### START CODE HERE ### (1 line) |
Exercise: Implement step 3, i.e. train the model. Choose the number of epochs and the batch size.
1 | ### START CODE HERE ### (1 line) |
Epoch 1/20
600/600 [==============================] - 3s 5ms/step - loss: 0.5316 - acc: 0.7200
Epoch 2/20
600/600 [==============================] - 2s 3ms/step - loss: 0.2036 - acc: 0.9350
Epoch 3/20
600/600 [==============================] - 2s 3ms/step - loss: 0.1294 - acc: 0.9783
Epoch 4/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0941 - acc: 0.9850
Epoch 5/20
600/600 [==============================] - 2s 4ms/step - loss: 0.0748 - acc: 0.9867
Epoch 6/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0610 - acc: 0.9883
Epoch 7/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0511 - acc: 0.9917
Epoch 8/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0464 - acc: 0.9900
Epoch 9/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0352 - acc: 0.9933
Epoch 10/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0270 - acc: 0.9967
Epoch 11/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0235 - acc: 0.9950
Epoch 12/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0267 - acc: 0.9950
Epoch 13/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0208 - acc: 0.9950
Epoch 14/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0142 - acc: 0.9983
Epoch 15/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0154 - acc: 0.9967
Epoch 16/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0146 - acc: 0.9967A: 1s - lo
Epoch 17/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0101 - acc: 0.9983
Epoch 18/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0187 - acc: 0.9950
Epoch 19/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0084 - acc: 1.0000
Epoch 20/20
600/600 [==============================] - 2s 3ms/step - loss: 0.0055 - acc: 1.0000
<keras.callbacks.History at 0x1188a2dd8>
Note that if you run fit()
again, the model
will continue to train with the parameters it has already learnt instead of reinitializing them.
Exercise: Implement step 4, i.e. test/evaluate the model.
1 | ### START CODE HERE ### (1 line) |
150/150 [==============================] - 0s 2ms/step
Loss = 0.0641684126854
Test Accuracy = 0.973333337307
If your happyModel()
function worked, you should have observed much better than random-guessing (50%) accuracy on the train and test sets. To pass this assignment, you have to get at least 75% accuracy.
To give you a point of comparison, our model gets around 95% test accuracy in 40 epochs (and 99% train accuracy) with a mini batch size of 16 and “adam” optimizer. But our model gets decent accuracy after just 2-5 epochs, so if you’re comparing different models you can also train a variety of models on just a few epochs and see how they compare.
If you have not yet achieved 75% accuracy, here’re some things you can play around with to try to achieve it:
- Try using blocks of CONV->BATCHNORM->RELU such as:
1 | X = Conv2D(32, (3, 3), strides = (1, 1), name = 'conv0')(X) |
until your height and width dimensions are quite low and your number of channels quite large (≈32 for example). You are encoding useful information in a volume with a lot of channels. You can then flatten the volume and use a fully-connected layer.
- You can use MAXPOOL after such blocks. It will help you lower the dimension in height and width.
- Change your optimizer. We find Adam works well.
- If the model is struggling to run and you get memory issues, lower your batch_size (12 is usually a good compromise)
- Run on more epochs, until you see the train accuracy plateauing.
Even if you have achieved 75% accuracy, please feel free to keep playing with your model to try to get even better results.
Note: If you perform hyperparameter tuning on your model, the test set actually becomes a dev set, and your model might end up overfitting to the test (dev) set. But just for the purpose of this assignment, we won’t worry about that here.
3 - Conclusion
Congratulations, you have solved the Happy House challenge!
Now, you just need to link this model to the front-door camera of your house. We unfortunately won’t go into the details of how to do that here.
What we would like you to remember from this assignment:
- Keras is a tool we recommend for rapid prototyping. It allows you to quickly try out different model architectures. Are there any applications of deep learning to your daily life that you’d like to implement using Keras?
- Remember how to code a model in Keras and the four steps leading to the evaluation of your model on the test set. Create->Compile->Fit/Train->Evaluate/Test.
4 - Test with your own image (Optional)
Congratulations on finishing this assignment. You can now take a picture of your face and see if you could enter the Happy House. To do that:
1. Click on “File” in the upper bar of this notebook, then click “Open” to go on your Coursera Hub.
2. Add your image to this Jupyter Notebook’s directory, in the “images” folder
3. Write your image’s name in the following code
4. Run the code and check if the algorithm is right (0 is unhappy, 1 is happy)!
The training/test sets were quite similar; for example, all the pictures were taken against the same background (since a front door camera is always mounted in the same position). This makes the problem easier, but a model trained on this data may or may not work on your own data. But feel free to give it a try!
1 | ### START CODE HERE ### |
[[ 1.]]
5 - Other useful functions in Keras (Optional)
Two other basic features of Keras that you’ll find useful are:
model.summary()
: prints the details of your layers in a table with the sizes of its inputs/outputsplot_model()
: plots your graph in a nice layout. You can even save it as “.png” using SVG() if you’d like to share it on social media ;). It is saved in “File” then “Open…” in the upper bar of the notebook.
Run the following code.
1 | happyModel.summary() |
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) (None, 64, 64, 3) 0
_________________________________________________________________
zero_padding2d_1 (ZeroPaddin (None, 66, 66, 3) 0
_________________________________________________________________
conv2d_1 (Conv2D) (None, 64, 64, 8) 224
_________________________________________________________________
batch_normalization_1 (Batch (None, 64, 64, 8) 32
_________________________________________________________________
activation_1 (Activation) (None, 64, 64, 8) 0
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 32, 32, 8) 0
_________________________________________________________________
zero_padding2d_2 (ZeroPaddin (None, 34, 34, 8) 0
_________________________________________________________________
conv2d_2 (Conv2D) (None, 32, 32, 16) 1168
_________________________________________________________________
batch_normalization_2 (Batch (None, 32, 32, 16) 64
_________________________________________________________________
activation_2 (Activation) (None, 32, 32, 16) 0
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 16, 16, 16) 0
_________________________________________________________________
zero_padding2d_3 (ZeroPaddin (None, 18, 18, 16) 0
_________________________________________________________________
conv2d_3 (Conv2D) (None, 16, 16, 32) 4640
_________________________________________________________________
batch_normalization_3 (Batch (None, 16, 16, 32) 128
_________________________________________________________________
activation_3 (Activation) (None, 16, 16, 32) 0
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 8, 8, 32) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 2048) 0
_________________________________________________________________
dense_1 (Dense) (None, 1) 2049
=================================================================
Total params: 8,305
Trainable params: 8,193
Non-trainable params: 112
_________________________________________________________________
1 | plot_model(happyModel, to_file='HappyModel.png') |