TensorFlow学习笔记(1)——conv2d函数的padding参数详解

时间:2022-11-25 14:08:35

conv2d函数原型

    tf.nn.conv2d ( input,  filter,  strides,  padding,  use_cudnn_on_gpu=None,  name=None )

参数说明:

    input:输入图像,shape为 [ batch,  in_height,   in_width,  in_channels ],例如 [ 1, 28, 28, 1 ]

    filter:卷积核,shape为 [ filter_height,  filter_width,  in_channels,  out_channels ],如 [ 5, 5, 1, 1 ] 

    strides:步长,一维向量,长度为 4,如 [ 1, 1, 1, 1 ]

    padding:string类型,取值为‘SAME’或‘VALID’,例如‘SAME’


第一种padding方式:‘SAME’

1、卷积后的Feature map尺寸的计算方式为:

    out_height = ceil ( float ( in_height )  /  float ( strides [1] ) )
    out_width  = ceil ( float ( in_width ) / float ( strides [2] ) )


2、例子:

    import  tensorflow  as  tf

    x_image  =  tf.Variable ( tf.random_normal ( [ 1, 28, 28, 1] ) )

    kernel  =  tf.Variable ( tf.random_normal ( [5, 5, 1, 1] ) ) 

    conv  =  tf.nn.conv2d ( x_image,  kernel,  strides= [ 1, 1, 1, 1 ],  padding='SAME' )

    with  tf.Session ()  as  sess: 

        sess.run ( tf.global_variables_initializer () ) 

        result = ( sess.run ( conv ) ) 

        print ( result.shape )


    程序运行结果:

    ====== RESTART: D:\Python_code\ML\test.py ======
    ( 1,  28,  28, 1 )
    >>> 


3、经过卷积后的Feature map尺寸的计算方式说明:

    out_height = ceil ( float ( in_height ) / float ( strides[1] ) ) = ceil ( float ( 28 ) / float ( 1 ) )  = 28
    out_width  = ceil ( float ( in_width ) / float ( strides[2] ) ) = ceil ( float ( 28 ) / float ( 1 ) )  = 28


第二种padding方式:‘VALID’

1、卷积后的Feature map尺寸的计算方式为:

    out_height = ceil ( float ( in_height - filter_height + 1 ) / float ( strides[1] ) )
    out_width  = ceil ( float ( in_width - filter_width + 1 ) / float ( strides[2] ) )


2、例子:

    import  tensorflow  as  tf

    x_image  =  tf.Variable ( tf.random_normal ( [ 1, 28, 28, 1] ) )

    kernel  =  tf.Variable ( tf.random_normal ( [5, 5, 1, 1] ) ) 

    conv  =  tf.nn.conv2d ( x_image,  kernel,  strides= [ 1, 1, 1, 1 ],  padding='VALID' )

    with  tf.Session ()  as  sess: 

        sess.run ( tf.global_variables_initializer () ) 

        result = ( sess.run ( conv ) ) 

        print ( result.shape )


    程序运行结果:

    ====== RESTART: D:\Python_code\ML\test.py ======
    ( 1,  24,  24, 1 )
    >>> 


3、经过卷积后的Feature map尺寸的计算方式说明:

    out_height = ceil ( float (i n_height - filter_height + 1 ) / float ( strides[1] ) ) = ceil ( float ( 28 - 5+ 1 )  / float ( 1 ) ) = 24
    out_width  = ceil ( float ( in_width - filter_width + 1 ) / float ( strides[2] ) ) = ceil ( float ( 28 - 5+ 1 )  / float ( 1 ) ) = 24