Advertisement
ERENARD63

Happy House using Keras

Apr 12th, 2018
411
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.33 KB | None | 0 0
  1.  
  2. # coding: utf-8
  3.  
  4. # # Keras tutorial - the Happy House
  5. #
  6. # Welcome to the first assignment of week 2. In this assignment, you will:
  7. # 1. 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.
  8. # 2. See how you can in a couple of hours build a deep learning algorithm.
  9. #
  10. # 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.
  11. #
  12. # 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!
  13.  
  14. # In[9]:
  15.  
  16. import numpy as np
  17. from keras import layers
  18. from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
  19. from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
  20. from keras.models import Model
  21. from keras.preprocessing import image
  22. from keras.utils import layer_utils
  23. from keras.utils.data_utils import get_file
  24. from keras.applications.imagenet_utils import preprocess_input
  25. import pydot
  26. from IPython.display import SVG
  27. from keras.utils.vis_utils import model_to_dot
  28. from keras.utils import plot_model
  29. from kt_utils import *
  30.  
  31. import keras.backend as K
  32. K.set_image_data_format('channels_last')
  33. import matplotlib.pyplot as plt
  34. from matplotlib.pyplot import imshow
  35.  
  36. get_ipython().magic('matplotlib inline')
  37.  
  38.  
  39. # **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(...)`.
  40.  
  41. # ## 1 - The Happy House
  42. #
  43. # 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.
  44. #
  45. # <img src="images/happy-house.jpg" style="width:350px;height:270px;">
  46. # <caption><center> <u> <font color='purple'> **Figure 1** </u><font color='purple'>  : **the Happy House**</center></caption>
  47. #
  48. #
  49. # 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.
  50. #
  51. # You have gathered pictures of your friends and yourself, taken by the front-door camera. The dataset is labbeled.
  52. #
  53. # <img src="images/house-members.png" style="width:550px;height:250px;">
  54. #
  55. # Run the following code to normalize the dataset and learn about its shapes.
  56.  
  57. # In[10]:
  58.  
  59. X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()
  60.  
  61. # Normalize image vectors
  62. X_train = X_train_orig/255.
  63. X_test = X_test_orig/255.
  64.  
  65. # Reshape
  66. Y_train = Y_train_orig.T
  67. Y_test = Y_test_orig.T
  68.  
  69. print ("number of training examples = " + str(X_train.shape[0]))
  70. print ("number of test examples = " + str(X_test.shape[0]))
  71. print ("X_train shape: " + str(X_train.shape))
  72. print ("Y_train shape: " + str(Y_train.shape))
  73. print ("X_test shape: " + str(X_test.shape))
  74. print ("Y_test shape: " + str(Y_test.shape))
  75.  
  76.  
  77. # **Details of the "Happy" dataset**:
  78. # - Images are of shape (64,64,3)
  79. # - Training: 600 pictures
  80. # - Test: 150 pictures
  81. #
  82. # It is now time to solve the "Happy" Challenge.
  83.  
  84. # ## 2 - Building a model in Keras
  85. #
  86. # Keras is very good for rapid prototyping. In just a short time you will be able to build a model that achieves outstanding results.
  87. #
  88. # Here is an example of a model in Keras:
  89. #
  90. # ```python
  91. # def model(input_shape):
  92. #     # Define the input placeholder as a tensor with shape input_shape. Think of this as your input image!
  93. #     X_input = Input(input_shape)
  94. #
  95. #     # Zero-Padding: pads the border of X_input with zeroes
  96. #     X = ZeroPadding2D((3, 3))(X_input)
  97. #
  98. #     # CONV -> BN -> RELU Block applied to X
  99. #     X = Conv2D(32, (7, 7), strides = (1, 1), name = 'conv0')(X)
  100. #     X = BatchNormalization(axis = 3, name = 'bn0')(X)
  101. #     X = Activation('relu')(X)
  102. #
  103. #     # MAXPOOL
  104. #     X = MaxPooling2D((2, 2), name='max_pool')(X)
  105. #
  106. #     # FLATTEN X (means convert it to a vector) + FULLYCONNECTED
  107. #     X = Flatten()(X)
  108. #     X = Dense(1, activation='sigmoid', name='fc')(X)
  109. #
  110. #     # Create model. This creates your Keras model instance, you'll use this instance to train/test the model.
  111. #     model = Model(inputs = X_input, outputs = X, name='HappyModel')
  112. #    
  113. #     return model
  114. # ```
  115. #
  116. # 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).
  117. #
  118. # **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()`.
  119. #
  120. # **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.
  121.  
  122. # In[11]:
  123.  
  124. # GRADED FUNCTION: HappyModel
  125.  
  126. def HappyModel(input_shape):
  127.     """
  128.    Implementation of the HappyModel.
  129.    
  130.    Arguments:
  131.    input_shape -- shape of the images of the dataset
  132.  
  133.    Returns:
  134.    model -- a Model() instance in Keras
  135.    """
  136.    
  137.     ### START CODE HERE ###
  138.     # Feel free to use the suggested outline in the text above to get started, and run through the whole
  139.     # exercise (including the later portions of this notebook) once. The come back also try out other
  140.     # network architectures as well.
  141.    
  142.     # Define the input placeholder as a tensor with shape input_shape. Think of this as your input image!
  143.     X_input = Input(input_shape)
  144.  
  145.     # Zero-Padding: pads the border of X_input with zeroes
  146.     X = ZeroPadding2D((3, 3))(X_input)
  147.  
  148.     # CONV -> BN -> RELU Block applied to X
  149.     X = Conv2D(32, (7, 7), strides = (1, 1), name = 'conv0')(X)
  150.     X = BatchNormalization(axis = 3, name = 'bn0')(X)
  151.     X = Activation('relu')(X)
  152.  
  153.     # MAXPOOL
  154.     X = MaxPooling2D((2, 2), name='max_pool')(X)
  155.  
  156.     # FLATTEN X (means convert it to a vector) + FULLYCONNECTED
  157.     X = Flatten()(X)
  158.     X = Dense(1, activation='sigmoid', name='fc')(X)
  159.  
  160.     # Create model. This creates your Keras model instance, you'll use this instance to train/test the model.
  161.     model = Model(inputs = X_input, outputs = X, name='HappyModel')
  162.  
  163.      
  164.     ### END CODE HERE ###
  165.    
  166.     return model
  167.  
  168.  
  169. # You have now built a function to describe your model. To train and test this model, there are four steps in Keras:
  170. # 1. Create the model by calling the function above
  171. # 2. Compile the model by calling `model.compile(optimizer = "...", loss = "...", metrics = ["accuracy"])`
  172. # 3. Train the model on train data by calling `model.fit(x = ..., y = ..., epochs = ..., batch_size = ...)`
  173. # 4. Test the model on test data by calling `model.evaluate(x = ..., y = ...)`
  174. #
  175. # If you want to know more about `model.compile()`, `model.fit()`, `model.evaluate()` and their arguments, refer to the official [Keras documentation](https://keras.io/models/model/).
  176. #
  177. # **Exercise**: Implement step 1, i.e. create the model.
  178.  
  179. # In[12]:
  180.  
  181. ### START CODE HERE ### (1 line)
  182. happyModel = HappyModel(input_shape = (64, 64, 3))
  183. # model = Model(inputs = X_input, outputs = X, name='ResNet50')
  184. #model = ResNet50(input_shape = (64, 64, 3), classes = 6)
  185. ### END CODE HERE ###
  186.  
  187.  
  188. # **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.
  189.  
  190. # In[14]:
  191.  
  192. ### START CODE HERE ### (1 line)
  193. happyModel.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])
  194. ### END CODE HERE ###
  195.  
  196.  
  197. # **Exercise**: Implement step 3, i.e. train the model. Choose the number of epochs and the batch size.
  198.  
  199. # In[17]:
  200.  
  201. ### START CODE HERE ### (1 line)
  202. happyModel.fit(X_train, Y_train, epochs = 40, batch_size = 16)
  203. ### END CODE HERE ###
  204.  
  205.  
  206. # Note that if you run `fit()` again, the `model` will continue to train with the parameters it has already learnt instead of reinitializing them.
  207. #
  208. # **Exercise**: Implement step 4, i.e. test/evaluate the model.
  209.  
  210. # In[18]:
  211.  
  212. ### START CODE HERE ### (1 line)
  213. preds = happyModel.evaluate(X_test, Y_test)
  214. ### END CODE HERE ###
  215. print()
  216. print ("Loss = " + str(preds[0]))
  217. print ("Test Accuracy = " + str(preds[1]))
  218.  
  219.  
  220. # If your `happyModel()` function worked, you should have observed much better than random-guessing (50%) accuracy on the train and test sets.
  221. #
  222. # 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.
  223. #
  224. # If you have not yet achieved a very good accuracy (let's say more than 80%), here're some things you can play around with to try to achieve it:
  225. #
  226. # - Try using blocks of CONV->BATCHNORM->RELU such as:
  227. # ```python
  228. # X = Conv2D(32, (3, 3), strides = (1, 1), name = 'conv0')(X)
  229. # X = BatchNormalization(axis = 3, name = 'bn0')(X)
  230. # X = Activation('relu')(X)
  231. # ```
  232. # 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.
  233. # - You can use MAXPOOL after such blocks. It will help you lower the dimension in height and width.
  234. # - Change your optimizer. We find Adam works well.
  235. # - If the model is struggling to run and you get memory issues, lower your batch_size (12 is usually a good compromise)
  236. # - Run on more epochs, until you see the train accuracy plateauing.
  237. #
  238. # Even if you have achieved a good accuracy, please feel free to keep playing with your model to try to get even better results.
  239. #
  240. # **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.
  241. #
  242.  
  243. # ## 3 - Conclusion
  244. #
  245. # Congratulations, you have solved the Happy House challenge!
  246. #
  247. # 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.
  248.  
  249. # <font color='blue'>
  250. # **What we would like you to remember from this assignment:**
  251. # - 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?
  252. # - 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.
  253.  
  254. # ## 4 - Test with your own image (Optional)
  255. #
  256. # 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:
  257. #     1. Click on "File" in the upper bar of this notebook, then click "Open" to go on your Coursera Hub.
  258. #     2. Add your image to this Jupyter Notebook's directory, in the "images" folder
  259. #     3. Write your image's name in the following code
  260. #     4. Run the code and check if the algorithm is right (0 is unhappy, 1 is happy)!
  261. #    
  262. # 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!
  263.  
  264. # In[ ]:
  265.  
  266. ### START CODE HERE ###
  267. img_path = 'images/my_image.jpg'
  268. ### END CODE HERE ###
  269. img = image.load_img(img_path, target_size=(64, 64))
  270. imshow(img)
  271.  
  272. x = image.img_to_array(img)
  273. x = np.expand_dims(x, axis=0)
  274. x = preprocess_input(x)
  275.  
  276. print(happyModel.predict(x))
  277.  
  278.  
  279. # ## 5 - Other useful functions in Keras (Optional)
  280. #
  281. # Two other basic features of Keras that you'll find useful are:
  282. # - `model.summary()`: prints the details of your layers in a table with the sizes of its inputs/outputs
  283. # - `plot_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.
  284. #
  285. # Run the following code.
  286.  
  287. # In[ ]:
  288.  
  289. happyModel.summary()
  290.  
  291.  
  292. # In[ ]:
  293.  
  294. plot_model(happyModel, to_file='HappyModel.png')
  295. SVG(model_to_dot(happyModel).create(prog='dot', format='svg'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement