Welcome to the first assignment of week 2. In this assignment, you will:
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!
import numpy as np
from keras import layers
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from keras.models import Model
from keras.preprocessing import image
from keras.utils import layer_utils
from keras.utils.data_utils import get_file
from keras.applications.imagenet_utils import preprocess_input
import pydot
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
from keras.utils import plot_model
from kt_utils import *
import keras.backend as K
K.set_image_data_format('channels_last')
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
%matplotlib inline
Using TensorFlow backend.
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(...)
.
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.
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()
# Normalize image vectors
X_train = X_train_orig/255.
X_test = X_test_orig/255.
# Reshape
Y_train = Y_train_orig.T
Y_test = Y_test_orig.T
print ("number of training examples = " + str(X_train.shape[0]))
print ("number of test examples = " + str(X_test.shape[0]))
print ("X_train shape: " + str(X_train.shape))
print ("Y_train shape: " + str(Y_train.shape))
print ("X_test shape: " + str(X_test.shape))
print ("Y_test shape: " + str(Y_test.shape))
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:
It is now time to solve the “Happy” Challenge.
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:
def model(input_shape):
# Define the input placeholder as a tensor with shape input_shape. Think of this as your input image!
X_input = Input(input_shape)
# Zero-Padding: pads the border of X_input with zeroes
X = ZeroPadding2D((3, 3))(X_input)
# CONV -> BN -> RELU Block applied to X
X = Conv2D(32, (7, 7), strides = (1, 1), name = 'conv0')(X)
X = BatchNormalization(axis = 3, name = 'bn0')(X)
X = Activation('relu')(X)
# MAXPOOL
X = MaxPooling2D((2, 2), name='max_pool')(X)
# FLATTEN X (means convert it to a vector) + FULLYCONNECTED
X = Flatten()(X)
X = Dense(1, activation='sigmoid', name='fc')(X)
# Create model. This creates your Keras model instance, you'll use this instance to train/test the model.
model = Model(inputs = X_input, outputs = X, name='HappyModel')
return model
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.
# GRADED FUNCTION: HappyModel
def HappyModel(input_shape):
"""
Implementation of the HappyModel.
Arguments:
input_shape -- shape of the images of the dataset
Returns:
model -- a Model() instance in Keras
"""
### START CODE HERE ###
# Feel free to use the suggested outline in the text above to get started, and run through the whole
# exercise (including the later portions of this notebook) once. The come back also try out other
# network architectures as well.
# 将输入占位符定义为一个带有input_shape形状的张量。把它看作是您的输入图像!!
# 底层是tensorflow ,其实是创建placeholder存放变量
X_input = Input(input_shape)
# 0填充: 用0填充 X_input
# 建立padding画布,主要适配不同图片尺寸或者避免边缘特征磨损的情况
X = ZeroPadding2D((3, 3))(X_input)
# CONV卷积层 -> BN批量归一化层 -> RELU Block激活函数 applied to X
##32 是过滤核的数量;(7,7)是过滤核的宽度和高度,strides是卷积的部长,name是对其进行命名
X = Conv2D(32, (7, 7), strides = (1, 1), name = 'conv0')(X)
"""axis讲解
keepdims=True 保持了结果维度
s0 = np.sum(a, axis=0, keepdims=True) # s0.shape = (1, 3)
s1 = np.sum(a, axis=1, keepdims=True) # s1.shape = (4, 1)
a.shape = (4, 3), 这样的话 axis 只能等于 0 or 1;(若 x.shape = (4, 4, 3), x 上的 axis 可以为 0 or 1 or 2)
观察 s0, 当 axis = 0 时, a.shape, (4, 3) 中的 4 将变成1, 其余维度不变化, 既 3 没变;
同样观察 s1, 当 axis = 1 时, a.shape, (4, 3) 中的 3 将变成1, 其余维度不变化, 既 4 没变;"""
#规范化,控制过拟合
X = BatchNormalization(axis = 3, name = 'bn0')(X)
#激活函数
X = Activation('relu')(X)
# MAXPOOL
X = MaxPooling2D((2, 2), name='max_pool')(X)
# 全连接,多维转为一维
X = Flatten()(X)
#激活函数,和全连接
X = Dense(1, activation='sigmoid', name='fc')(X)
#创建模型。这将创建Keras模型实例,您将使用该实例来培训/测试模型
model = Model(inputs = X_input, outputs = X, name='HappyModel')
### END CODE HERE ###
return model
You have now built a function to describe your model. To train and test this model, there are four steps in Keras:
model.compile(optimizer = "...", loss = "...", metrics = ["accuracy"])
model.fit(x = ..., y = ..., epochs = ..., batch_size = ...)
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.
### START CODE HERE ### (1 line)
happyModel = HappyModel(X_train.shape[1:]) #第一个样本
### END CODE HERE ###
WARNING: Logging before flag parsing goes to stderr.
W0827 21:10:33.131934 6764 deprecation_wrapper.py:119] From C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.
W0827 21:10:33.151934 6764 deprecation_wrapper.py:119] From C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py:517: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.
W0827 21:10:33.154934 6764 deprecation_wrapper.py:119] From C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py:4138: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead.
W0827 21:10:33.174934 6764 deprecation_wrapper.py:119] From C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py:174: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead.
W0827 21:10:33.175934 6764 deprecation_wrapper.py:119] From C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py:181: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.
W0827 21:10:33.243934 6764 deprecation_wrapper.py:119] From C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py:1834: The name tf.nn.fused_batch_norm is deprecated. Please use tf.compat.v1.nn.fused_batch_norm instead.
W0827 21:10:33.296934 6764 deprecation_wrapper.py:119] From C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py:3976: The name tf.nn.max_pool is deprecated. Please use tf.nn.max_pool2d instead.
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.
### START CODE HERE ### (1 line)
#选择adam作为优化器,二分类交交叉商作为损失函数
happyModel.compile(optimizer = "adam", loss = "binary_crossentropy", metrics = ["accuracy"])
### END CODE HERE ###
W0827 21:10:37.478934 6764 deprecation_wrapper.py:119] From C:\ProgramData\Anaconda3\lib\site-packages\keras\optimizers.py:790: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.
W0827 21:10:37.506934 6764 deprecation.py:323] From C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\nn_impl.py:180: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
Exercise: Implement step 3, i.e. train the model. Choose the number of epochs and the batch size.
### START CODE HERE ### (1 line)
#这里的参数epoch的作用就不多解释了,不能太小。影响较大的是batch_size,刚开始我设的是50,最后震荡的厉害,就说明批量选小了
happyModel.fit(x=X_train,y=Y_train,epochs=40,batch_size=100)
### END CODE HERE ###
Epoch 1/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0150 - acc: 0.9967
Epoch 2/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0158 - acc: 0.9967
Epoch 3/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0142 - acc: 0.9950
Epoch 4/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0138 - acc: 0.9967
Epoch 5/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0145 - acc: 0.9950
Epoch 6/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0165 - acc: 0.9950
Epoch 7/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0190 - acc: 0.9933
Epoch 8/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0210 - acc: 0.9950
Epoch 9/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0213 - acc: 0.9933
Epoch 10/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0133 - acc: 1.0000
Epoch 11/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0122 - acc: 1.0000
Epoch 12/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0139 - acc: 0.9967
Epoch 13/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0108 - acc: 1.0000
Epoch 14/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0108 - acc: 0.9983
Epoch 15/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0106 - acc: 0.9967
Epoch 16/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0134 - acc: 0.9983
Epoch 17/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0129 - acc: 0.9967
Epoch 18/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0183 - acc: 0.9950
Epoch 19/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0116 - acc: 0.9983
Epoch 20/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0148 - acc: 0.9933
Epoch 21/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0138 - acc: 0.9967
Epoch 22/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0089 - acc: 1.0000
Epoch 23/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0091 - acc: 1.0000
Epoch 24/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0077 - acc: 1.0000
Epoch 25/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0082 - acc: 1.0000
Epoch 26/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0108 - acc: 1.0000
Epoch 27/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0090 - acc: 1.0000
Epoch 28/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0070 - acc: 0.9983
Epoch 29/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0076 - acc: 0.9983
Epoch 30/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0076 - acc: 1.0000
Epoch 31/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0074 - acc: 0.9983
Epoch 32/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0061 - acc: 1.0000
Epoch 33/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0054 - acc: 1.0000
Epoch 34/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0047 - acc: 1.0000
Epoch 35/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0044 - acc: 1.0000
Epoch 36/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0040 - acc: 1.0000
Epoch 37/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0043 - acc: 1.0000
Epoch 38/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0044 - acc: 1.0000
Epoch 39/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0037 - acc: 1.0000
Epoch 40/40
600/600 [==============================] - 2s 4ms/step - loss: 0.0040 - acc: 1.0000
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.
### START CODE HERE ### (1 line)
preds = happyModel.evaluate(x=X_test,y=Y_test)
### END CODE HERE ###
print()
print ("Loss = " + str(preds[0]))
print ("Test Accuracy = " + str(preds[1]))
150/150 [==============================] - 0s 3ms/step
Loss = 0.053998040705919265
Test Accuracy = 0.9799999976158142
If your happyModel()
function worked, you should have observed much better than random-guessing (50%) accuracy on the train and test sets.
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 a very good accuracy (let’s say more than 80%), here’re some things you can play around with to try to achieve it:
X = Conv2D(32, (3, 3), strides = (1, 1), name = 'conv0')(X)
X = BatchNormalization(axis = 3, name = 'bn0')(X)
X = Activation('relu')(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.
当模型表现不好时,你可以改变的参数
Even if you have achieved a good 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.
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.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!
### START CODE HERE ###
img_path = 'images/face_smale.jpg' #路径
### END CODE HERE ###
img = image.load_img(img_path, target_size=(64, 64)) #读图,并规范大小
imshow(img) #显示图片
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
print(happyModel.predict(x))
[[1.]]
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.
happyModel.summary()
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) (None, 64, 64, 3) 0
_________________________________________________________________
zero_padding2d_1 (ZeroPaddin (None, 70, 70, 3) 0
_________________________________________________________________
conv0 (Conv2D) (None, 64, 64, 32) 4736
_________________________________________________________________
bn0 (BatchNormalization) (None, 64, 64, 32) 128
_________________________________________________________________
activation_1 (Activation) (None, 64, 64, 32) 0
_________________________________________________________________
max_pool (MaxPooling2D) (None, 32, 32, 32) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 32768) 0
_________________________________________________________________
fc (Dense) (None, 1) 32769
=================================================================
Total params: 37,633
Trainable params: 37,569
Non-trainable params: 64
_________________________________________________________________
#此处有坑,需要安装Graphviz等东西,时间问题,希望有时间的朋友可以探讨一下,本人就先跳过继续后边内容了
plot_model(happyModel, to_file='HappyModel.png')
SVG(model_to_dot(happyModel).create(prog='dot', format='svg'))
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\pydot.py in create(self, prog, format, encoding)
1914 arguments=arguments,
-> 1915 working_dir=tmp_dir,
1916 )
C:\ProgramData\Anaconda3\lib\site-packages\pydot.py in call_graphviz(program, arguments, working_dir, **kwargs)
135 stdout=subprocess.PIPE,
--> 136 **kwargs
137 )
C:\ProgramData\Anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
774 errread, errwrite,
--> 775 restore_signals, start_new_session)
776 except:
C:\ProgramData\Anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
1177 os.fspath(cwd) if cwd is not None else None,
-> 1178 startupinfo)
1179 finally:
FileNotFoundError: [WinError 2] 系统找不到指定的文件。
During handling of the above exception, another exception occurred:
FileNotFoundError Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\vis_utils.py in _check_pydot()
25 # to check the pydot/graphviz installation.
---> 26 pydot.Dot.create(pydot.Dot())
27 except OSError:
C:\ProgramData\Anaconda3\lib\site-packages\pydot.py in create(self, prog, format, encoding)
1921 prog=prog)
-> 1922 raise OSError(*args)
1923 else:
FileNotFoundError: [WinError 2] "dot" not found in path.
During handling of the above exception, another exception occurred:
OSError Traceback (most recent call last)
in
1 #此处有坑,需要安装Graphviz,时间问题,此处忽略
2 get_ipython().run_line_magic('matplotlib', 'inline')
----> 3 plot_model(happyModel, to_file='HappyModel.png')
4 SVG(model_to_dot(happyModel).create(prog='dot', format='svg'))
C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\vis_utils.py in plot_model(model, to_file, show_shapes, show_layer_names, rankdir)
130 'LR' creates a horizontal plot.
131 """
--> 132 dot = model_to_dot(model, show_shapes, show_layer_names, rankdir)
133 _, extension = os.path.splitext(to_file)
134 if not extension:
C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\vis_utils.py in model_to_dot(model, show_shapes, show_layer_names, rankdir)
53 from ..models import Sequential
54
---> 55 _check_pydot()
56 dot = pydot.Dot()
57 dot.set('rankdir', rankdir)
C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\vis_utils.py in _check_pydot()
27 except OSError:
28 raise OSError(
---> 29 '`pydot` failed to call GraphViz.'
30 'Please install GraphViz (https://www.graphviz.org/) '
31 'and ensure that its executables are in the $PATH.')
OSError: `pydot` failed to call GraphViz.Please install GraphViz (https://www.graphviz.org/) and ensure that its executables are in the $PATH.