Python中卷积函数入门学习

本人最近在进行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进行加速。

注意:①在使用时必须指定不同维度的步长。

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值