本人最近在进行CNN神经网络的前向传播相关工作,其中用到了卷积操作,因此对Python自带的卷积函数进行简单了解,以方便自己的使用。
1、函数一:tf.nn.convolution(input, filter, padding, strides=None,dilation_rate=None,name=None,data_format=None)
测试代码如下:
import tensorflow as tf
# input的要求格式是[batch_size] + [input_spatial_shape](height高度、width宽度) + [in_channels];
input_data = tf.constant(
[
[
[ [1],[2],[3],[4],[5], ],
[ [0],[0],[0],[0],[0], ],
[ [1],[2],[3],[4],[5], ],
[ [1],[2],[3],[4],[5], ],
[ [0],[0],[0],[0],[0] ]
]
] )
# filter的要求格式是[spatial_filter_shape](height高度、width宽度) + [channel](in_channels, out_channel)
filter_layer1 = tf.constant(
[
[ [[0]],[[1]],[[0]] ],
[ [[1]],[[1]],[[1]] ],
[ [[1]],[[0]],[[1]] ]
]
)
# print(input_data)
conv_result = tf.nn.convolution(input_data, filter_layer1, padding='VALID');
print(conv_result)
输出如下:
个人理解:在使用本函数时,其input与filter的数据格式必须严格按照函数规定的传入,若不一样,则IDE会报错。关于padding参数,可取“VALID”与“SAME”,通过查询资料,该填充方式为自动填充,其结果具有不确定性,因此在这里不做过多讨论。
注意:①在使用constant时,左括号必须紧跟constant,例:constant(
②在constant函数的第一维索引中,必须在[ ]后输入“,”,否则会报错“list indices must be integers or slices, not tuple”。
2、函数二:tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None)
测试代码如下:
conv_result2 = tf.nn.conv2d(input_data, filter_layer1, strides=[1,1,1,1], padding='VALID')
输出如下:
个人理解:该函数与tf.nn.convolution基本相同,但该函数指定了计算卷积的维度即2维卷积。use_cudnn_on_gpu该参数含义为是否使用GPU进行加速。
注意:①在使用时必须指定不同维度的步长。