TensorFlow卷积函数tf.nn.conv2d

tf.nn.conv2d

在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
)

Returns:
A Tensor. 

input:

指需要做卷积的输入图像(tensor),具有[batch,in_height,in_width,in_channels]这样的4维shape,分别是图片数量、图片高度、图片宽度、图片通道数,数据类型为float32或float64。

filter:

相当于CNN中的卷积核,它是一个tensor,shape是[filter_height,filter_width,in_channels,out_channels]:滤波器高度、宽度、图像通道数、滤波器个数,数据类型和input相同。

strides:

卷积在每一维的步长,一般为一个一维向量,长度为4,一般为[1,stride,stride,1]。

padding:

定义元素边框和元素内容之间的空间,只能是‘SAME’(边缘填充)或者‘VALID’(边缘不填充)。

return:

返回值是Tensor

例子

例1(1个通道1个输出)

假设我们用一个5*5的矩阵来模拟图片,定义一个2*2点的卷积核

例1

 

import tensorflow as tf
input = tf.Variable(tf.constant(1.0, shape=[1, 5, 5, 1]))
filter = tf.Variable(tf.constant([-1.0, 0, 0, -1], shape=[2, 2, 1, 1]))
op = tf.nn.conv2d(input, filter, strides=[1, 2, 2, 1], padding='SAME')

init = tf.global_variables_initializer()
with tf.Session() as sess:
  sess.run(init)
  print("op:\n",sess.run(op))

输出如下:

op:
[[[[-2.]
[-2.]
[-1.]]

[[-2.]
[-2.]
[-1.]]

[[-1.]
[-1.]
[-1.]]]]

实际过程就是:

 

 

padding='SAME',这种情况tensorflow会先在边侧补0(优先右侧和下方),然后经过卷积操作得到结果。

例2(1个通道3个输出)

我们用三个filter来创造三个输出:

 

多通道

 

import tensorflow as tf
input = tf.Variable(tf.constant(1.0, shape=[1, 5, 5, 1]))

raw = tf.Variable(tf.constant([-1.0, 0, 0, -1], shape=[2, 2, 1, 1]))
filter=tf.tile(raw,[1,1,1,3])

op=tf.nn.conv2d(input,filter, strides=[1, 2, 2, 1], padding='SAME')

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print("op:\n",sess.run(op))

输出结果:

output

三个filter相同,输出了三个相同的结果(按列看)

例3(2个通道2个输出)

例3.png

代码:

 

import tensorflow as tf
input = tf.Variable(tf.constant(1.0, shape=[1, 3, 3, 2]))

raw = tf.Variable(tf.constant([-1, 9.0, 0, 0,0,0,1,0], shape=[2, 2, 2, 1]))
filter=tf.tile(raw,[1,1,1,2])

op=tf.nn.conv2d(input,filter, strides=[1, 2, 2, 1], padding='SAME')

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(filter))
    print("\nop:\n",sess.run(op))

输出结果:

filter:

filter.png

这是两个filter,红框就是一个卷积核,绿框黄框分别对应着两个通道。

卷积结果:

 

output.png

输出就是两个2x2的矩阵。



作者:PanDong
链接:https://www.jianshu.com/p/c72af2ff5393
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值