吴恩达deeplearning Lesson4 Week2 keras入门 2个案例:happyhouse+resnet

本文主要是介绍吴恩达deeplearning Lesson4 Week2 keras入门 2个案例:happyhouse+resnet,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

吴恩达deeplearning Lesson4 Week2

  • Keras+-+Tutorial+-+Happy+House+v2
    • input
    • 正确率50%
    • compile中 loss 选择问题
    • 代码
  • Residual+Networks+-+v2
    • 找不到resnets_utils
    • 思路
    • keras 细节

Keras±+Tutorial±+Happy+House+v2

遇到两个问题。
model函数建立如下:


def HappyModel(input_shape):"""Implementation of the HappyModel.Arguments:input_shape -- shape of the images of the datasetReturns: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. 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, (5, 5), strides = (1, 1), name = 'conv0')(X)X = BatchNormalization(axis = 3, name = 'bn0')(X)X = Activation('relu')(X)X = MaxPooling2D((2, 2), name='max_pool0')(X)X = Conv2D(16, (3, 3), strides = (1, 1), name = 'conv1')(X)X = BatchNormalization(axis = 3, name = 'bn1')(X)X = Activation('relu')(X)# MAXPOOLX = MaxPooling2D((2, 2), name='max_pool1')(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')### END CODE HERE ###return model

input

这里的 X_input = Input(input_shape) 的input_shape 代表的是每张图片的shape,在本例子中是(64,64,3)。并不是(m,64,64,3)。
input的意义是告诉model要处理的每一个样本是什么样的,再去做后续处理。

正确率50%

我将例子给的model搭建顺序直接放到code中,发现永远都是正确率50%
例子放上来,下面是错误示范:

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

我在想是不是我的设置问题,去discuss论坛上看,被各路豪杰一顿误导。

最后看到其中一位大哥说 是因为例子的误导,如果照搬例子则会如此,我果断加了一层conv、bn、relu、pool就达到了正常的水平(代码在keras大标题下面)

compile中 loss 选择问题

一开始去keras官方文档的例子看,使用例子推荐的categorical_crossentropy:

happyModel.compile(optimizer = 'Adamax', loss='categorical_crossentropy', metrics = ["accuracy"])

报错。
因为本例子的标签只有0和1,所以更改为’binary_crossentropy’

代码

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 inlineX_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))
def HappyModel(input_shape):"""Implementation of the HappyModel.Arguments:input_shape -- shape of the images of the datasetReturns: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. 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, (5, 5), strides = (1, 1), name = 'conv0')(X)X = BatchNormalization(axis = 3, name = 'bn0')(X)X = Activation('relu')(X)X = MaxPooling2D((2, 2), name='max_pool0')(X)X = Conv2D(16, (3, 3), strides = (1, 1), name = 'conv1')(X)X = BatchNormalization(axis = 3, name = 'bn1')(X)X = Activation('relu')(X)# MAXPOOLX = MaxPooling2D((2, 2), name='max_pool1')(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')### END CODE HERE ###return model
happyModel = HappyModel((X_train.shape[1],X_train.shape[2],X_train.shape[3]))
happyModel.compile(optimizer = 'Adamax', loss='binary_crossentropy', metrics = ["accuracy"])
happyModel.fit(x =X_train, y = Y_train, epochs = 100, batch_size = 64)
### 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 [==============================] - 1s 5ms/step

Loss = 0.0807561850548
Test Accuracy = 0.960000003974

Residual+Networks±+v2

找不到resnets_utils

找不到因为本地没有,文件缺省了。
去Coursera的课程notebook上下载对应文件。
我的chrome上Coursera的notebook经常上不去,反而用edge效果不错。而且国内连接时断时续,点不进去的时候,点之前点开的notebook,file->open 可以向上退一级文件夹选择需要的文件。并放置到指定位置。
在这里插入图片描述

思路

通过构建
identity_block(X, f, filters, stage, block)
convolutional_block(X, f, filters, stage, block, s = 2)
两个模块,并将模块进行堆叠来实现下图的resnet-50
在这里插入图片描述

keras 细节

层函数后面的括号代表这层的输入,如果是resnet,记得更改。如下

X_shortcut = Conv2D(F3, (1, 1), strides = (s,s),padding = 'valid', name = conv_name_base + '1', kernel_initializer = glorot_uniform(seed=0))(X_shortcut)
X_shortcut = BatchNormalization(axis = 3, name = bn_name_base + '1')(X_shortcut)
#这里后面括号注意更改

注意tensor形状相同才行进行层相加操作。

    # Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines)X =  Add()([X, X_shortcut])#形状相同才能相加X = Activation('relu')(X)

这篇关于吴恩达deeplearning Lesson4 Week2 keras入门 2个案例:happyhouse+resnet的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/561166

相关文章

MySQL 中的 JSON 查询案例详解

《MySQL中的JSON查询案例详解》:本文主要介绍MySQL的JSON查询的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql 的 jsON 路径格式基本结构路径组件详解特殊语法元素实际示例简单路径复杂路径简写操作符注意MySQL 的 J

Python Transformers库(NLP处理库)案例代码讲解

《PythonTransformers库(NLP处理库)案例代码讲解》本文介绍transformers库的全面讲解,包含基础知识、高级用法、案例代码及学习路径,内容经过组织,适合不同阶段的学习者,对... 目录一、基础知识1. Transformers 库简介2. 安装与环境配置3. 快速上手示例二、核心模

Python中使用正则表达式精准匹配IP地址的案例

《Python中使用正则表达式精准匹配IP地址的案例》Python的正则表达式(re模块)是完成这个任务的利器,但你知道怎么写才能准确匹配各种合法的IP地址吗,今天我们就来详细探讨这个问题,感兴趣的朋... 目录为什么需要IP正则表达式?IP地址的基本结构基础正则表达式写法精确匹配0-255的数字验证IP地

MySQL高级查询之JOIN、子查询、窗口函数实际案例

《MySQL高级查询之JOIN、子查询、窗口函数实际案例》:本文主要介绍MySQL高级查询之JOIN、子查询、窗口函数实际案例的相关资料,JOIN用于多表关联查询,子查询用于数据筛选和过滤,窗口函... 目录前言1. JOIN(连接查询)1.1 内连接(INNER JOIN)1.2 左连接(LEFT JOI

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

MySQL中实现多表查询的操作方法(配sql+实操图+案例巩固 通俗易懂版)

《MySQL中实现多表查询的操作方法(配sql+实操图+案例巩固通俗易懂版)》本文主要讲解了MySQL中的多表查询,包括子查询、笛卡尔积、自连接、多表查询的实现方法以及多列子查询等,通过实际例子和操... 目录复合查询1. 回顾查询基本操作group by 分组having1. 显示部门号为10的部门名,员

Python FastAPI入门安装使用

《PythonFastAPI入门安装使用》FastAPI是一个现代、快速的PythonWeb框架,用于构建API,它基于Python3.6+的类型提示特性,使得代码更加简洁且易于绶护,这篇文章主要介... 目录第一节:FastAPI入门一、FastAPI框架介绍什么是ASGI服务(WSGI)二、FastAP

Python爬虫selenium验证之中文识别点选+图片验证码案例(最新推荐)

《Python爬虫selenium验证之中文识别点选+图片验证码案例(最新推荐)》本文介绍了如何使用Python和Selenium结合ddddocr库实现图片验证码的识别和点击功能,感兴趣的朋友一起看... 目录1.获取图片2.目标识别3.背景坐标识别3.1 ddddocr3.2 打码平台4.坐标点击5.图

使用Navicat工具比对两个数据库所有表结构的差异案例详解

《使用Navicat工具比对两个数据库所有表结构的差异案例详解》:本文主要介绍如何使用Navicat工具对比两个数据库test_old和test_new,并生成相应的DDLSQL语句,以便将te... 目录概要案例一、如图两个数据库test_old和test_new进行比较:二、开始比较总结概要公司存在多