【TensorFlow】conv2d函数参数解释以及padding理解

卷积conv2d

CNN在深度学习中有着举足轻重的地位,主要用于特征提取。在TensorFlow中涉及的函数是tf.nn.conv2d。

tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=True, data_format=“NHWC”, dilations=[1, 1, 1, 1], name=None)

  • input 代表做卷积的输入图像的Tensor,其shape要求为[batch, in_height, in_width, in_channels],具体含义是[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数],数据类型为float32或float64;
  • filter 相当于CNN中的卷积核,该Tensor的shape要求为[filter_height, filter_width, in_channels, out_channels],具体含义是[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数],要求类型与参数input相同,filter的通道数要求与input的in_channels一致,即第三维in_channels,就是参数input的第四维;
  • strides [1,stride_h,stride_w,1]步长,即卷积核每次移动的步长;
  • padding string类型的量,只能是"SAME","VALID"其中之一,这个值决定了不同的卷积方式;

输出结果是shape为[batch, out_height, out_width, out_channels],batch取决于input,out_channels取决于filter,而out_height与out_width取决于所有参数,参考示意图

  • SAME模式
    • out_height = ceil ( float ( in_height ) / float ( stride_h) )
    • out_width = ceil ( float ( in_width ) / float ( stride_w ) )
  • VALID模式
    • out_height = ceil(float(in_height - filter_height + 1) / float(stride_h))
    • out_width = ceil(float(in_width - filter_width + 1) / float(stride_w))

补的方式如下:

  • 补的行数:pad_along_height = max((out_height - 1) * strides[1] + filter_height - in_height, 0)

  • 补的列数:pad_along_width = max((out_width - 1) * strides[2] + filter_width - in_width, 0)

  • pad_top = pad_along_height // 2

  • pad_bottom = pad_along_height - pad_top

  • pad_left = pad_along_width // 2

  • pad_right = pad_along_width - pad_left

测试实例

import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import tensorflow as tfinput = tf.Variable(tf.random_normal([1,16,64,3]))
filter = tf.Variable(tf.random_normal([3,5,3,32]))
op = tf.nn.conv2d(input, filter, strides=[1, 2, 2, 1], padding='VALID')with tf.Session() as sess:sess.run(tf.global_variables_initializer())res = (sess.run(op))print (res.shape)# (1, 7, 30, 32)

空洞卷积atrous_conv2d

tf.nn.atrous_conv2d(value, filters, rate, padding, name=None)

  • input 代表做卷积的输入图像的Tensor,其shape要求为[batch, in_height, in_width, in_channels],具体含义是[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数],数据类型为float32或float64;
  • filter 相当于CNN中的卷积核,该Tensor的shape要求为[filter_height, filter_width, in_channels, out_channels],具体含义是[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数],要求类型与参数input相同,filter的通道数要求与input的in_channels一致,即第三维in_channels,就是参数input的第四维;
  • rate 要求是一个int型的正数,正常的卷积操作应该会有stride(即卷积核的滑动步长),但是空洞卷积是没有stride参数的,这一点尤其要注意。取而代之,它使用了新的rate参数,那么rate参数有什么用呢?它定义为我们在输入图像上卷积时的采样间隔,你可以理解为卷积核当中穿插了(rate-1)数量的“0”,把原来的卷积核插出了很多“洞洞”,这样做卷积时就相当于对原图像的采样间隔变大了。具体怎么插得,可以看后面更加详细的描述。此时我们很容易得出rate=1时,就没有0插入,此时这个函数就变成了普通卷积;
  • padding 填充模式,取值只能为“SAME”或“VALID”;

A positive int32. The stride with which we sample input values across the height and width dimensions. Equivalently, the rate by which we upsample the filter values by inserting zeros across the height and width dimensions. In the literature, the same parameter is sometimes called input stride or dilation.

输出shape为

  • VALID
    [batch, height - 2 * (filter_width - 1), width - 2 * (filter_height - 1), out_channels].

  • SAME
    [batch, height, width, out_channels].

深入理解:

  • 参考:【Tensorflow】tf.nn.atrous_conv2d如何实现空洞卷积?的示意图
  • 查看函数说明,其中有优化部分
    延伸阅读:
  • 对于xception非常好的理解
  • 【Tensorflow】tf.nn.depthwise_conv2d如何实现深度卷积?
  • 【Tensorflow】tf.nn.separable_conv2d如何实现深度可分卷积?

反卷积conv2d_transpose

反卷积操作是卷积的反向

tf.nn.conv2d_transpose(value, filter, output_shape, strides, padding=‘SAME’, data_format=‘NHWC’, name=None)

  • value 指需要做反卷积的输入图像,它要求是一个Tensor
  • filter 卷积核,它要求是一个Tensor,具有[filter_height, filter_width, out_channels, in_channels]这样的shape,具体含义是[卷积核的高度,卷积核的宽度,卷积核个数,图像通道数]
  • output_shape 反卷积操作输出的shape
  • strides 反卷积时在图像每一维的步长,这是一个一维的向量,长度4
  • padding string类型的量,只能是"SAME","VALID"其中之一,这个值决定了不同的卷积方式
  • data_format string类型的量,'NHWC’和’NCHW’其中之一,这是tensorflow新版本中新加的参数,它说明了value参数的数据格式。'NHWC’指tensorflow标准的数据格式[batch, height, width, in_channels],‘NCHW’指Theano的数据格式,[batch, in_channels,height, width],当然默认值是’NHWC’

在这里解释一下output_shape这个参数,反卷积操作是卷积的反向,在卷积计算中输出维度是上取整,那么这就说明输入维度可能是多个,所以在反卷积计算时需要用户给出这个输入维度。

后续学习资料

  • 卷积神经网络CNN经典模型整理Lenet,Alexnet,Googlenet,VGG,Deep Residual Learning
  • ResNet解析
  • ResNetV2:ResNet深度解析
import osos.environ["CUDA_VISIBLE_DEVICES"] = "-1"import tensorflow as tf
tf.enable_eager_execution()tf.set_random_seed(1234)def conv2d_same(inputs, kernel, stride,rate=1):if stride == 1:return tf.nn.conv2d(inputs, kernel, [1, stride, stride, 1], padding='SAME')else:kernel_size = kernel.shape.as_list()[0]kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)pad_total = kernel_size_effective - 1pad_beg = pad_total // 2pad_end = pad_total - pad_begpaddings = [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]]print(paddings)inputs_ = tf.pad(inputs, paddings)print(tf.squeeze(inputs_))same_conv = tf.nn.conv2d(inputs_, kernel, [1, stride, stride, 1], padding='VALID')print("=============conv2d_same=============")print(tf.squeeze(same_conv))def conv2d_fun(inputs, kernel, stride, padding):conv = tf.nn.conv2d(inputs, kernel, [1, stride, stride, 1], padding=padding)print("============" + padding + "==" + "S("+str(stride)+")" + "============")print(tf.squeeze(conv))def test(k_size):src = tf.random_uniform((1, k_size, k_size, 1), 0, 5, tf.int32, seed=0)src = tf.cast(src, tf.float32)print("=============inputs{}==============".format(src.shape.as_list()))print(tf.squeeze(src))kernel = tf.random_uniform((3, 3, 1, 1), -1, 2, tf.int32, seed=0)kernel = tf.cast(kernel, tf.float32)print("=============inputs{}==============".format(kernel.shape.as_list()))print(tf.squeeze(kernel))conv2d_fun(src, kernel, 1, "SAME")conv2d_fun(src, kernel, 2, "SAME")conv2d_fun(src, kernel, 1, "VALID")conv2d_fun(src, kernel, 2, "VALID")conv2d_same(src, kernel, 2)if __name__ == "__main__":test(7)print("=" * 80)test(8)

参考

  • tensorflow conv2d的padding解释以及参数解释
  • conv2d函数的padding参数解释
  • TensorFlow中CNN的两种padding方式“SAME”和“VALID”
  • What is the difference between ‘SAME’ and ‘VALID’ padding in tf.nn.max_pool of tensorflow?
  • tf.nn.dynamic_rnn的输出outputs和state含义

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/508644.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

卷积与傅立叶变换

一、卷积 1、一维的卷积 连续: 在泛函分析中,卷积是通过两个函数f(x)f(x)和g(x)g(x)生成第三个函数的一种算子,它代表的意义是:两个函数中的一个(我取g(x)g(x),可以任意取)函数,把g(x)g(x)经过翻转平移,…

海明纠错码工作原理

海明纠错码 海明码(Hamming Code)是一个可以有多个校验位,具有检测并纠正一位错误代码的纠错码,所以它也仅用于信道特性比较好的环境中,如以太局域网中,因为如果信道特性不好的情况下,出现的错…

OpenCV-Python bindings是如何生成的(1)

翻译自How OpenCV-Python Bindings Works? 目标 学习 OpenCV-Python bindings是如何生成的如何为Python扩展新的opencv模块 OpenCV-Python bindings是如何生成的 在OpenCV里,所有算法都是用C实现的。但是这些算法可以在别的语言里使用,比如Python&…

OpenCV-Python bindings是如何生成的(2)

OpenCV-Python bindings生成流程 通过上篇文章和opencv python模块中的CMakeLists.txt文件,可以了解到opencv-python bindings生成的整个流程: 生成headers.txt文件 将每个模块的头文件添加到list中,通过一些关键词过滤掉一些不需要扩展的头文件&#x…

【TensorFlow】学习资源汇总以及知识总结

官方资源 官方网站 https://tensorflow.org 非翻墙神器不能访问也(关键是我用了翻墙神器也没能访问)伪官方网站 https://tensorflow.google.cn/ 墙内的人可以查阅的资料github https://github.com/tensorflow/tensorflow官方提供的models以及tutorial h…

机器学习资源锦集

http://www.cnblogs.com/pinard 十年码农,对数学统计学,数据挖掘,机器学习,大数据平台,大数据平台应用开发,大数据可视化感兴趣。github 深度学习 【深度学习】批归一化(Batch Normalization&…

获取训练数据的方式

下载搜狗词库 https://pinyin.sogou.com/dict/ 在官网搜索相关的词库下载,比如地名等,然后使用脚本将此条转换成txt保存, 来源 # -*- coding: utf-8 -*- import os import sys import struct # 主要两部分 # 1.全局拼音表,貌似…

浅谈python MRO与Mixin模式

MRO(Method Resolution Order) In object-oriented programming languages with multiple inheritance, the diamond problem (sometimes referred to as the “deadly diamond of death”) is an ambiguity that arises when two classes B and C inherit from A, and class D…

CentOS7开发环境搭建(2)

关闭SELinux # 查看 $ getenforce Disabled $ sestatus SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root directory: /etc/selinux Loaded policy name: targeted Current mode: …

IntelliJ IDEA开发环境应用

安装 下载windows压缩包获取帮助: idea.medeming.com/jihuoma 常用设置 全局设置,对新建的工程生效 【File】【Other Settings】【Setings for New Projects…】 比如配置maven的路径以及配置文件的路径,基本设置一次即可,不需要每次新建工…

tcp状态机-三次握手-四次挥手以及常见面试题

TCP状态机介绍 在网络协议栈中,目前只有TCP提供了一种面向连接的可靠性数据传输。而可靠性,无非就是保证,我发给你的,你一定要收到。确保中间的通信过程中,不会丢失数据和乱序。在TCP保证可靠性数据传输的实现来看&am…

Visual studio Code的C/C++开发环境搭建

文章目录VS CodeC/C环境配置环境准备使用实例基于 VSCode 的远程开发平台环境准备参考VS Code Visual Studio Code(简称VS Code)是一个由微软开发,同时支持Windows 、 Linux和macOS等操作系统且开放源代码的代码编辑器,它支持测试…

Linux网络编程--文件描述符

文件描述符 在Unix和Unix-like操作系统中,文件描述符(file descriptor, FD)是一个文件或者像pipe或者network socket等之类的输入/输出源的唯一标识。 文件描述符通常是一个非负整数,负数通常代表无值或者错误。 文件描述符是POSIX API的一部分。每个除…

深信服 linux软件开发面试题整理

1、结构体可以进行比较 int memcmp ( const void * ptr1, const void * ptr2, size_t num ); Compare two blocks of memory Compares the first num bytes of the block of memory pointed by ptr1 to the first num bytes pointed by ptr2, returning zero if they all match…

大端小端模式判断以及数据转换

简介 在计算机系统中,我们是以字节为单位的,每个地址单元都对应着一个字节,一个字节为 8bit。但是在C语言中除了8bit的char之外,还有16bit的short型,32bit的long型(要看具体的编译器)&#xff…

MSYS2下搭建Qt开发环境

最近随意浏览了一下俺们大省会城市的招聘信息,发现C招聘中涉及Qt经验的要求有不少,为了牛奶和面包,决心深入一下Qt开发。本篇文章由此而出。 Qt 关于Qt的人生经历在这不在累赘,资料随处可得,这里只记录干货。 环境搭…

CentOS7开发环境搭建(1)

文章目录BIOS开启VT支持U盘安装系统(2019-03-11)CentOS DNS配置CentOS网络配置配置静态IP克隆虚拟机网卡名称变更 CentOS6.5时间配置安装VMWare-tools用户管理 (2019-03-15 7.6.1810)给一般账号 root 权限Samba服务配置安装必备软件获取本机公网ipyum源和第三方库源管理配置本地…

ACM 欧拉公式

给出一个数X,求小于X的与X互质的数的个数,使用欧拉公式。 如果x1*x2*...*xnX,则个数nX*(1-1/x1)*(1-/x2)*... 使用这个的题目,超典型 相遇周期(HDOJ)

HDU 1495 非常可乐(BFS)

思路 最难在于想到这道题是BFS&#xff0c;想到之后只有六种情况就很好理解了。 代码 #include<stdio.h> #include<string.h> #include<math.h> #include<queue> using namespace std; int a,b,s; struct shui {int count;int ha,hb,hs; }t,t1; int m…

NBU计算机专业期末考试记录

考试科目&#xff1a;操作系统 软件工程 数据库 计算机网络 JAVA高级应用 汇编 计算机算法设计 操作系统&#xff1a;题目比较简单&#xff0c;这学期的大题有写读写互斥的代码、求平均磁道数、银行家算法、页面调度算法的缺页次数计算。期中考试有参考价值&#xff0c;要看懂…