吴恩达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

相关文章

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进行比较:二、开始比较总结概要公司存在多

SpringBoot实现动态插拔的AOP的完整案例

《SpringBoot实现动态插拔的AOP的完整案例》在现代软件开发中,面向切面编程(AOP)是一种非常重要的技术,能够有效实现日志记录、安全控制、性能监控等横切关注点的分离,在传统的AOP实现中,切... 目录引言一、AOP 概述1.1 什么是 AOP1.2 AOP 的典型应用场景1.3 为什么需要动态插

Golang操作DuckDB实战案例分享

《Golang操作DuckDB实战案例分享》DuckDB是一个嵌入式SQL数据库引擎,它与众所周知的SQLite非常相似,但它是为olap风格的工作负载设计的,DuckDB支持各种数据类型和SQL特性... 目录DuckDB的主要优点环境准备初始化表和数据查询单行或多行错误处理和事务完整代码最后总结Duck

MySQL不使用子查询的原因及优化案例

《MySQL不使用子查询的原因及优化案例》对于mysql,不推荐使用子查询,效率太差,执行子查询时,MYSQL需要创建临时表,查询完毕后再删除这些临时表,所以,子查询的速度会受到一定的影响,本文给大家... 目录不推荐使用子查询和JOIN的原因解决方案优化案例案例1:查询所有有库存的商品信息案例2:使用EX

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Hadoop企业开发案例调优场景

需求 (1)需求:从1G数据中,统计每个单词出现次数。服务器3台,每台配置4G内存,4核CPU,4线程。 (2)需求分析: 1G / 128m = 8个MapTask;1个ReduceTask;1个mrAppMaster 平均每个节点运行10个 / 3台 ≈ 3个任务(4    3    3) HDFS参数调优 (1)修改:hadoop-env.sh export HDFS_NAMENOD

性能分析之MySQL索引实战案例

文章目录 一、前言二、准备三、MySQL索引优化四、MySQL 索引知识回顾五、总结 一、前言 在上一讲性能工具之 JProfiler 简单登录案例分析实战中已经发现SQL没有建立索引问题,本文将一起从代码层去分析为什么没有建立索引? 开源ERP项目地址:https://gitee.com/jishenghua/JSH_ERP 二、准备 打开IDEA找到登录请求资源路径位置

深入探索协同过滤:从原理到推荐模块案例

文章目录 前言一、协同过滤1. 基于用户的协同过滤(UserCF)2. 基于物品的协同过滤(ItemCF)3. 相似度计算方法 二、相似度计算方法1. 欧氏距离2. 皮尔逊相关系数3. 杰卡德相似系数4. 余弦相似度 三、推荐模块案例1.基于文章的协同过滤推荐功能2.基于用户的协同过滤推荐功能 前言     在信息过载的时代,推荐系统成为连接用户与内容的桥梁。本文聚焦于

【区块链 + 人才服务】可信教育区块链治理系统 | FISCO BCOS应用案例

伴随着区块链技术的不断完善,其在教育信息化中的应用也在持续发展。利用区块链数据共识、不可篡改的特性, 将与教育相关的数据要素在区块链上进行存证确权,在确保数据可信的前提下,促进教育的公平、透明、开放,为教育教学质量提升赋能,实现教育数据的安全共享、高等教育体系的智慧治理。 可信教育区块链治理系统的顶层治理架构由教育部、高校、企业、学生等多方角色共同参与建设、维护,支撑教育资源共享、教学质量评估、