[Tensorflow] convolution卷积和pooling池化

本文详细介绍了TensorFlow中卷积操作tf.nn.conv2d及池化操作tf.nn.max_pool和tf.nn.avg_pool的使用方法,并通过实例展示了两种不同填充方式(SAME与VALID)的效果对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、卷积与池化

(1)convol卷积  tf.nn.conv2d

tf.nn.conv2d(input,           #tensor。shape为[batch, in_height, in_width, in_channels]
  filter,                     #python list。 [filter_height, filter_width, in_channels, out_channels]
  strides,                    #输入的input四维stride。如[1,1,1,1]。一般第一维为1(不跳过batch中的样本),第四维也是1(不跳过某一个特征图)
  padding,                    #SAME:不填充。VALID填充
  use_cudnn_on_gpu=None, 
  data_format=None, 
  name=None)

(2)pooling池化 tf.nn.max_pool 、tf.nn.avg_pool

tf.nn.max_pool(value,   #A 4-D Tensor with shape [batch, height, width, channels] and type tf.float32
  ksize,                #一般为[1,x,x,1]。The size of the window for each dimension of the input tensor。
  strides,              #输入的input四维stride。如[1,1,1,1]
  padding,              #SAME 、VALID
  data_format='NHWC', 
  name=None)

tf.nn.avg_pool(value,
  ksize,
  strides,
  padding,
  data_format='NHWC',
  name=None
  )

二、关于padding(SAME、VALID)

import tensorflow as tf
sess=tf.Session()
x=tf.constant([i for i in range(0,9)],shape=[1,3,3,1],dtype=tf.float32)
W=tf.Variable(tf.constant(1,shape=[3,3,1,1],dtype=tf.float32))

conv_same=tf.nn.conv2d(x,W,strides=[1,1,1,1],padding="SAME") 
conv_valid=tf.nn.conv2d(x,W,strides=[1,1,1,1],padding="VALID")

#(1) padding后的shape
print(conv_same.get_shape())   #shape:[1,9,9,1]
print(conv_valid.get_shape())  #shape:[1,7,7,1]
"""
SAME : 卷积后大小与原来一样(这里没有测试strides大于1的情况)
VALID: 卷积后大小减少filter_size-1
"""

#(2) padding方式:在x的上下左右各加一行padding。(而非只在右下添加)
sess.run(tf.global_variables_initializer())
print(sess.run(conv_valid))

"""
结论:
x=[[0,1,2]
   [3,4,5]
   [6,7,8]]
其中卷积核 W为3*3的值为1的矩阵
conv_same=
  [[8,15,12]            #8=0+1+3+4    12=1+2+4+5
   [21,36,27]
   [20,33,24]]
"""


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值