吴恩达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间隙锁

《六个案例搞懂mysql间隙锁》MySQL中的间隙是指索引中两个索引键之间的空间,间隙锁用于防止范围查询期间的幻读,本文主要介绍了六个案例搞懂mysql间隙锁,具有一定的参考价值,感兴趣的可以了解一下... 目录概念解释间隙锁详解间隙锁触发条件间隙锁加锁规则案例演示案例一:唯一索引等值锁定存在的数据案例二:

MySQL 表的内外连接案例详解

《MySQL表的内外连接案例详解》本文给大家介绍MySQL表的内外连接,结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录表的内外连接(重点)内连接外连接表的内外连接(重点)内连接内连接实际上就是利用where子句对两种表形成的笛卡儿积进行筛选,我

Python中OpenCV与Matplotlib的图像操作入门指南

《Python中OpenCV与Matplotlib的图像操作入门指南》:本文主要介绍Python中OpenCV与Matplotlib的图像操作指南,本文通过实例代码给大家介绍的非常详细,对大家的学... 目录一、环境准备二、图像的基本操作1. 图像读取、显示与保存 使用OpenCV操作2. 像素级操作3.

Java Stream.reduce()方法操作实际案例讲解

《JavaStream.reduce()方法操作实际案例讲解》reduce是JavaStreamAPI中的一个核心操作,用于将流中的元素组合起来产生单个结果,:本文主要介绍JavaStream.... 目录一、reduce的基本概念1. 什么是reduce操作2. reduce方法的三种形式二、reduce

Spring Boot 整合 Redis 实现数据缓存案例详解

《SpringBoot整合Redis实现数据缓存案例详解》Springboot缓存,默认使用的是ConcurrentMap的方式来实现的,然而我们在项目中并不会这么使用,本文介绍SpringB... 目录1.添加 Maven 依赖2.配置Redis属性3.创建 redisCacheManager4.使用Sp

springboot项目redis缓存异常实战案例详解(提供解决方案)

《springboot项目redis缓存异常实战案例详解(提供解决方案)》redis基本上是高并发场景上会用到的一个高性能的key-value数据库,属于nosql类型,一般用作于缓存,一般是结合数据... 目录缓存异常实践案例缓存穿透问题缓存击穿问题(其中也解决了穿透问题)完整代码缓存异常实践案例Red

Nginx使用Keepalived部署web集群(高可用高性能负载均衡)实战案例

《Nginx使用Keepalived部署web集群(高可用高性能负载均衡)实战案例》本文介绍Nginx+Keepalived实现Web集群高可用负载均衡的部署与测试,涵盖架构设计、环境配置、健康检查、... 目录前言一、架构设计二、环境准备三、案例部署配置 前端 Keepalived配置 前端 Nginx

POI从入门到实战轻松完成EasyExcel使用及Excel导入导出功能

《POI从入门到实战轻松完成EasyExcel使用及Excel导入导出功能》ApachePOI是一个流行的Java库,用于处理MicrosoftOffice格式文件,提供丰富API来创建、读取和修改O... 目录前言:Apache POIEasyPoiEasyExcel一、EasyExcel1.1、核心特性

MySQL 复合查询案例详解

《MySQL复合查询案例详解》:本文主要介绍MySQL复合查询案例详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录基本查询回顾多表笛卡尔积子查询与where子查询多行子查询多列子查询子查询与from总结合并查询(不太重要)union基本查询回顾查询

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚