我是靠谱客的博主 欢喜硬币,这篇文章主要介绍Tensorflow 卷积层实现,现在分享给大家,希望可以做个参考。

在TensorFlow中,可以通过自定义权值的底层实现方式搭建神经网络,也可以直接调用现成的卷积层类的高层方式快速搭建复杂网络。

卷积运算输出大小公式:
h’ = (h+2Ph-k)/s + 1(向下取整)
w’ = (w+2
Pw-k)/s + 1(向下取整)
卷积核的大小k、步长s、填充数p、输入的高h和宽w

1、自定义权值
在TensorFlow中,通过tf.nn.conv2d函数可以实现2D卷积运算。

复制代码
1
2
3
4
5
6
7
8
9
10
#模拟输入 x = tf.random.normal([5,5,5,3]) #创建4个大小通道为3的3×3的卷积核 w = tf.random.normal([3,3,3,4]) out = tf.nn.conv2d(x,w,strides=1,padding=[[0,0],[0,0],[0,0],[0,0]]) out ''' <tf.Tensor: shape=(5, 3, 3, 4), dtype=float32, numpy=... '''

其中padding = [[0,0],[上,下],[左,右],[0,0]]。

复制代码
1
2
3
4
5
6
7
8
9
x = tf.random.normal([5,5,5,3]) w = tf.random.normal([3,3,3,4]) #上下左右个添加一个单位 out = tf.nn.conv2d(x,w,strides=1,padding=[[0,0],[1,1],[1,1],[0,0]]) out ''' <tf.Tensor: shape=(5, 5, 5, 4), dtype=float32, numpy=... '''

设置参数padding=‘SAME’、strides=1可以直接得到输入、输出同大小的卷积层。

复制代码
1
2
3
4
5
6
7
8
x = tf.random.normal([5,5,5,3]) w = tf.random.normal([3,3,3,4]) out = tf.nn.conv2d(x,w,strides=1,padding='SAME') out ''' <tf.Tensor: shape=(5, 5, 5, 4), dtype=float32, numpy=... '''

当步长大于1时,设置padding='SAME’使得输出高、宽将减少为原来的1/s。

复制代码
1
2
3
4
5
6
7
8
x = tf.random.normal([5,5,5,3]) w = tf.random.normal([3,3,3,4]) out = tf.nn.conv2d(x,w,strides=2,padding='SAME') out ''' <tf.Tensor: shape=(5, 3, 3, 4), dtype=float32, numpy=... '''

给网络设置偏置向量

复制代码
1
2
3
4
5
6
x = tf.random.normal([5,5,5,3]) w = tf.random.normal([3,3,3,4]) out = tf.nn.conv2d(x,w,strides=1,padding='SAME') b = tf.zeros([4]) out = out+b

2、卷积层
通过卷积层类layers.Conv2D可以不需要手动定义卷积核W和偏置b,在新建卷积层类时,只需要指定卷积核数量参数filters,卷积核大小kernel_size,步长strides,填充padding等。

复制代码
1
2
3
4
5
6
7
8
#创建了4个3×3大小的卷积核的卷积层,步长为1,padding为'SAME' layer = layers.Conv2D(4,kernel_size=3,strides=1,padding='SAME') out = layer(x) out ''' <tf.Tensor: shape=(5, 5, 5, 4), dtype=float32, numpy=... '''
复制代码
1
2
3
4
5
6
7
8
#4个4×3大小的卷积核,竖直方向步长=2,水平方向步长=3 layer = layers.Conv2D(4,kernel_size=(4,3),strides=(2,3),padding='SAME') out = layer(x) out ''' <tf.Tensor: shape=(5, 3, 2, 4), dtype=float32, numpy=... '''

在类Conv2D中,保存了卷积核张量W和偏置b,可以通过类成员trainable_variables直接返回W和b的列表。

复制代码
1
2
3
4
5
6
7
8
9
10
layer.trainable_variables ''' [<tf.Variable 'conv2d_5/kernel:0' shape=(4, 3, 3, 4) dtype=float32, numpy= array([[[[ 0.08817413, -0.25375998, 0.11716652, 0.23988143], [ 0.0737316 , 0.04550338, 0.02249208, 0.04421049], [-0.09486812, -0.03205609, 0.00232354, 0.0853363 ]], ...... <tf.Variable 'conv2d_5/bias:0' shape=(4,) dtype=float32, numpy=array([0., 0., 0., 0.], dtype=float32)>] '''

最后

以上就是欢喜硬币最近收集整理的关于Tensorflow 卷积层实现的全部内容,更多相关Tensorflow内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部