TensorFlow 卷积层

TensorFlow 卷积层

 

让我们看下如何在 TensorFlow 里面实现 CNN。

TensorFlow 提供了 tf.nn.conv2d() 和 tf.nn.bias_add() 函数来创建你自己的卷积层。

 1 # Output depth
 2 k_output = 64
 3 
 4 # Image Properties
 5 image_width = 10
 6 image_height = 10
 7 color_channels = 3
 8 
 9 # Convolution filter
10 filter_size_width = 5
11 filter_size_height = 5
12 
13 # Input/Image
14 input = tf.placeholder(
15     tf.float32,
16     shape=[None, image_height, image_width, color_channels])
17 
18 # Weight and bias
19 weight = tf.Variable(tf.truncated_normal(
20     [filter_size_height, filter_size_width, color_channels, k_output]))
21 bias = tf.Variable(tf.zeros(k_output))
22 
23 # Apply Convolution
24 conv_layer = tf.nn.conv2d(input, weight, strides=[1, 2, 2, 1], padding='SAME')
25 # Add bias
26 conv_layer = tf.nn.bias_add(conv_layer, bias)
27 # Apply activation function
28 conv_layer = tf.nn.relu(conv_layer)

上述代码用了 tf.nn.conv2d() 函数来计算卷积,weights 作为滤波器,[1, 2, 2, 1] 作为 strides。TensorFlow 对每一个 input 维度使用一个单独的 stride 参数,[batch, input_height, input_width, input_channels]。我们通常把 batch 和 input_channels (strides 序列中的第一个第四个)的 stride 设为 1

你可以专注于修改 input_height 和 input_width, batch 和 input_channels 都设置成 1。input_height 和 input_width strides 表示滤波器在input 上移动的步长。上述例子中,在 input 之后,设置了一个 5x5 ,stride 为 2 的滤波器。

tf.nn.bias_add() 函数对矩阵的最后一维加了偏置项。

原文地址:https://www.cnblogs.com/HL-blog/p/9296048.html