一、卷积与池化
(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]]
"""