本文节选自吴恩达老师《深度学习专项课程》编程作业,在此表示感谢。

课程链接:https://www.deeplearning.ai/deep-learning-specialization/

Welcome to the first assignment of week 2. In this assignment, you will:

  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.
  2. 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 - The Happy House

2 - Building a model in Keras

3 - Conclusion

4 - Other useful functions in Keras


import numpy as np
#import tensorflow as tf
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

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.

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.Tprint ("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))

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:

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 zeroesX = ZeroPadding2D((3, 3))(X_input)# CONV -> BN -> RELU Block applied to XX = Conv2D(32, (7, 7), strides = (1, 1), name = 'conv0')(X)X = BatchNormalization(axis = 3, name = 'bn0')(X)X = Activation('relu')(X)# MAXPOOLX = MaxPooling2D((2, 2), name='max_pool')(X)# FLATTEN X (means convert it to a vector) + FULLYCONNECTEDX = 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.

def HappyModel(input_shape):"""Implementation of the HappyModel.Arguments:input_shape -- shape of the images of the datasetReturns:model -- a Model() instance in Keras"""# 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. X_input = Input(input_shape)X = ZeroPadding2D((1,1))(X_input)x = Conv2D(8, (3,3), strides=(1,1))(X)X = BatchNormalization(axis=3)(X)X = Activation('relu')(X)X = MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid')(X)X = ZeroPadding2D(padding=(1, 1))(X)X = Conv2D(16, kernel_size=(3,3), strides=(1,1))(X)X = BatchNormalization(axis=3)(X)X = Activation('relu')(X)X = MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid')(X)X = ZeroPadding2D(padding=(1, 1))(X)X = Conv2D(32, kernel_size=(3,3), strides=(1,1))(X)X = BatchNormalization(axis=3)(X)X = Activation('relu')(X)X = MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid')(X)# FCX = Flatten()(X)Y = Dense(1, activation='sigmoid')(X)model = Model(inputs = X_input, outputs = Y, name='HappyModel')return model

You have now built a function to describe your model. To train and test this model, there are four steps in Keras:

  1. Create the model by calling the function above
  2. Compile the model by calling model.compile(optimizer = "...", loss = "...", metrics = ["accuracy"])
  3. Train the model on train data by calling model.fit(x = ..., y = ..., epochs = ..., batch_size = ...)
  4. 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.

happyModel = HappyModel((64,64,3))

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.

import kerashappyModel.compile(optimizer=keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0), loss='binary_crossentropy', metrics=['accuracy'])

Exercise: Implement step 3, i.e. train the model. Choose the number of epochs and the batch size.

happyModel.fit(x=X_train, y=Y_train, batch_size=16, epochs=20)
preds = happyModel.evaluate(x=X_test, y=Y_test)print()
print ("Loss = " + str(preds[0]))
print ("Test Accuracy = " + str(preds[1]))

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:

    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.

  • 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 - Other useful functions in Keras

wo 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/outputs
  • 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.

Run the following code.

happyModel.summary()plot_model(happyModel, to_file='HappyModel.png')
SVG(model_to_dot(happyModel).create(prog='dot', format='svg'))

11.深度学习练习:Keras tutorial - the Happy House(推荐)相关推荐

  1. 深度学习框架Keras的安装

    原文链接:https://blog.csdn.net/qingzhuochenfu/article/details/51187603 本人已经将最新博客更新转移至个人网站了,欢迎来访~~ SCP-17 ...

  2. 深度学习和Keras 简介

    随着近年来人工智能(AI)技术的大热,相信读者们对"人工智能""机器学习" 和"深度学习"这几个词汇已经耳熟能详.那么,这三者之间是什么关系 ...

  3. 【深度学习】Keras加载权重更新模型训练的教程(MobileNet)

    [深度学习]Keras加载权重更新模型训练的教程(MobileNet) 文章目录 1 重新训练 2 keras常用模块的简单介绍 3 使用预训练模型提取特征(口罩检测) 4 总结 1 重新训练 重新建 ...

  4. 【深度学习】Keras和Tensorflow框架使用区别辨析

    [深度学习]Keras和Tensorflow框架使用区别辨析 文章目录 1 概述 2 Keras简介 3 Tensorflow简介 4 使用tensorflow的几个小例子 5 Keras搭建CNN ...

  5. 【深度学习】Keras实现回归和二分类问题讲解

    [深度学习]Keras实现回归和二分类问题讲解 文章目录 [深度学习]Keras实现回归和二分类问题讲解 1 回归问题1.1 波士顿房价预测数据集1.2 构建基准模型1.3 数据预处理1.4 超参数 ...

  6. DL框架之Keras:深度学习框架Keras框架的简介、安装(Python库)、相关概念、Keras模型使用、使用方法之详细攻略

    DL框架之Keras:深度学习框架Keras框架的简介.安装(Python库).相关概念.Keras模型使用.使用方法之详细攻略 目录 Keras的简介 1.Keras的特点 2.Keras四大特性 ...

  7. 【深度学习】Keras vs PyTorch vs Caffe:CNN实现对比

    作者 | PRUDHVI VARMA 编译 | VK 来源 | Analytics Indiamag 在当今世界,人工智能已被大多数商业运作所应用,而且由于先进的深度学习框架,它非常容易部署.这些深度 ...

  8. 简易的深度学习框架Keras代码解析与应用

    北京 | 深度学习与人工智能研修12月23-24日 再设经典课程 重温深度学习阅读全文> 正文约12690个字,22张图,预计阅读时间:32分钟. 总体来讲keras这个深度学习框架真的很&qu ...

  9. Machine Learning Mastery 博客文章翻译:深度学习与 Keras

    目录 Keras 中神经网络模型的 5 步生命周期 在 Python 迷你课程中应用深度学习 Keras 深度学习库的二元分类教程 如何用 Keras 构建多层感知器神经网络模型 如何在 Keras ...

  10. halcon19.11深度学习关于分类入门案例

    目录 halcon19.11深度学习分类 关于配置环境 准备训练集 训练数据集 评估模型 测试模型 halcon19.11深度学习分类 关于配置环境 首先,如果你想使用halcon19.11学习深度学 ...

最新文章

  1. 细数二十世纪最伟大的10大算法
  2. python与excel的差别-python对Excel按条件进行内容补充(推荐)
  3. UOJ #214 合唱队形 (概率期望计数、DP、Min-Max容斥)
  4. ft2232驱动安装方法_ST-Link资料03_ST-Link固件升级、驱动下载安装方法
  5. 石头机器人红灯快闪_机器人集体“快闪”活动爆红网络 “我是AI”与您相约智能新时代...
  6. linux监控任务跑满,Linux服务器带宽和CPU跑满或跑高排查
  7. Java架构师知识体系汇总
  8. log4j记录日志到sqlserver数据库
  9. Python正则表达式常用flag含义与用法详解
  10. asp.net Ajax表单提交 二种方式数据处理 asp.net
  11. 云服务器怎么配置文件,云服务器网卡怎么配置文件
  12. 现场调试——win7 X64安装VS2017闪退之kb4474419 终极办法
  13. 7z文件格式及其源码的分析(四)
  14. 基于Web的个人网页响应式页面设计与实现 HTML+CSS+JavaScript(web前端网页制作课作业)
  15. 基于Springboot开发实现买卖三方二手商品交易网站
  16. 五、使用Python操作数据库
  17. [转] 高度近视也不用带眼镜了 只要有恒心,坚持三年,即使800度近视也可以根治。
  18. 平台程序微信平台开发应用的签名
  19. 【交换篇】06. 升级固件 ❀ C3750-E ❀ CISCO 交换机
  20. fastai入门教程和基本概念

热门文章

  1. oracle t44,SecureFiles LOBs基础知识之存储篇
  2. phpstudy(自己电脑主机做服务器,手机网站界面打不开)
  3. linux下c 链接mongodb,Linux下mongoDB下载与安装
  4. php给留言分配id_简单实现PHP留言板功能
  5. python2发送http不编码_[转]Python 2.x中常见字符编码和解码方面的错误及其解决办法...
  6. mfc 设置子窗口只打开一遍_MFC 判断子窗体是不是已经打开,避免重复创建
  7. python接口自动化测试框架实战从设计到开发_Python接口自动化测试框架实战 从设计到开发...
  8. php session存到redis,php Session存储到Redis的方法
  9. des 向量 java_在JAVA中使用DES算法
  10. yytextview多种格式_iOS YYText的使用笔记一(YYTextView图文编辑器)