tensorflow卷積層&池化層

卷積層

tensorflow提供了tf.nn.conv2d()和tf.nn.bias_add()函數來創建卷積層
下面示例用tf.nn.conv2d()函數來創建一個卷積層

# Output depth
k_output = 64

# Image Properties
image_width = 10
image_height = 10
color_channels = 3

# Convolution filter
filter_size_width = 5
filter_size_height = 5

# Input/Image
input = tf.placeholder(
    tf.float32,
    shape=[None, image_height, image_width, color_channels])

# Weight and bias
weight = tf.Variable(tf.truncated_normal(
    [filter_size_height, filter_size_width, color_channels, k_output]))
bias = tf.Variable(tf.zeros(k_output))

# Apply Convolution
conv_layer = tf.nn.conv2d(input=input,
                          filter=weights,
                          strides=[1, 2, 2, 1],
                          padding='SAME')
# Add bias
conv_layer = tf.nn.bias_add(conv_layer, bias)
# Apply activation function
conv_layer = tf.nn.relu(conv_layer)

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() 函數對矩陣的最後一維加了偏置項。

池化層

tensorflow 最大池化

TensorFlow 提供了 tf.nn.max_pool() 函數,用於對卷積層實現 最大池化

conv_layer = tf.nn.conv2d(input, weight, strides=[1, 2, 2, 1], padding='SAME')
conv_layer = tf.nn.bias_add(conv_layer, bias)
conv_layer = tf.nn.relu(conv_layer)
# Apply Max Pooling
conv_layer = tf.nn.max_pool(
    conv_layer,
    ksize=[1, 2, 2, 1],
    strides=[1, 2, 2, 1],
    padding='SAME')

tf.nn.max_pool() 函數實現最大池化時, ksize參數是濾波器大小,strides參數是步長。2x2 的濾波器配合 2x2 的步長是常用設定。

ksize 和 strides 參數也被構建爲四個元素的列表,每個元素對應 input tensor 的一個維度 ([batch, height, width, channels]),對 ksize 和 strides 來說,batch 和 channel 通常都設置成 1。
最大池化示例:
設置
H = height, W = width, D = depth
輸入維度是 4x4x5 (HxWxD)
濾波器大小 2x2 (HxW)
stride 的高和寬都是 2 (S)
新的高和寬的公式是:
new_height = (input_height - filter_height)/S + 1
new_width = (input_width - filter_width)/S + 1
所以最後得到的結果爲:
width = (4 - 2)/2 + 1 = 2
height = (4 - 2)/2 + 1 = 2
depth = 5

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章