TensorFlow 池化层

在 TensorFlow 中使用池化层

在下面的练习中,你需要设定池化层的大小,strides,以及相应的 padding。你可以参考 tf.nn.max_pool()。Padding 与卷积 padding 的原理一样。

说明

  1. 完成 maxpool 函数中所有的 TODO

  2. 设定 stridespadding 和 ksize 使得池化的结果维度为 (1, 2, 2, 1)

"""
Set the values to `strides` and `ksize` such that
the output shape after pooling is (1, 2, 2, 1).
"""
import tensorflow as tf
import numpy as np

# `tf.nn.max_pool` requires the input be 4D (batch_size, height, width, depth)
# (1, 4, 4, 1)
x = np.array([
    [0, 1, 0.5, 10],
    [2, 2.5, 1, -8],
    [4, 0, 5, 6],
    [15, 1, 2, 3]], dtype=np.float32).reshape((1, 4, 4, 1))
X = tf.constant(x)

def maxpool(input):
    # TODO: Set the ksize (filter size) for each dimension (batch_size, height, width, depth)
    ksize = [?, ?, ?, ?]
    # TODO: Set the stride for each dimension (batch_size, height, width, depth)
    strides = [?, ?, ?, ?]
    # TODO: set the padding, either 'VALID' or 'SAME'.
    padding = ?
    # https://www.tensorflow.org/versions/r0.11/api_docs/python/nn.html#max_pool
    return tf.nn.max_pool(input, ksize, strides, padding)
    
out = maxpool(X)

方案

这是我的做法。注意:有不止一种方法得到正确的输出维度,你的答案可能会跟我的有所不同。

def maxpool(input):
    ksize = [1, 2, 2, 1]
    strides = [1, 2, 2, 1]
    padding = 'VALID'
    return tf.nn.max_pool(input, ksize, strides, padding)

我想要把输入的 (1, 4, 4, 1) 转变成 (1, 2, 2, 1)。padding 方法我选择 'VALID'。我觉得他更容易理解,也得到了我想要的结果。

out_height = ceil(float(in_height - filter_height + 1) / float(strides[1]))
out_width  = ceil(float(in_width - filter_width + 1) / float(strides[2]))

替换入值:

out_height = ceil(float(4 - 2 + 1) / float(2)) = ceil(1.5) = 2
out_width  = ceil(float(4 - 2 + 1) / float(2)) = ceil(1.5) = 2
深度在池化的时候不变,所以不用担心。

猜你喜欢

转载自www.cnblogs.com/fuhang/p/9264992.html