Exemple #1
0
def model(is_training, reuse, num_classes=5, dropout_keep_prob=0.5):
    common_args = common_layer_args(is_training, reuse)
    conv_args = make_args(batch_norm=True,
                          activation=prelu,
                          w_init=initz.he_normal(scale=1),
                          untie_biases=False,
                          **common_args)
    conv_args_fm = make_args(w_init=initz.he_normal(scale=1),
                             untie_biases=False,
                             **common_args)
    pool_args = make_args(padding='SAME', **common_args)
    inputs = input((None, crop_size[1], crop_size[0], 3), **common_args)
    with tf.variable_scope('squeezenet', values=[inputs]):
        net = conv2d(inputs, 96, stride=(2, 2), name='conv1', **conv_args)
        net = max_pool(net, name='maxpool1', **pool_args)
        net = fire_module(net, 16, 64, name='fire2', **conv_args_fm)
        net = bottleneck_simple(net, 16, 64, name='fire3', **conv_args_fm)
        net = batch_norm(net,
                         activation_fn=tf.nn.relu,
                         name='fire3_bn',
                         is_training=is_training,
                         reuse=reuse)
        net = fire_module(net, 32, 128, name='fire4', **conv_args_fm)
        net = max_pool(net, name='maxpool4', **pool_args)
        net = bottleneck_simple(net, 32, 128, name='fire5', **conv_args_fm)
        net = batch_norm(net,
                         activation_fn=tf.nn.relu,
                         name='fire5_bn',
                         is_training=is_training,
                         reuse=reuse)
        net = fire_module(net, 48, 192, name='fire6', **conv_args_fm)
        net = bottleneck_simple(net, 48, 192, name='fire7', **conv_args_fm)
        net = batch_norm(net,
                         activation_fn=tf.nn.relu,
                         name='fire7_bn',
                         is_training=is_training,
                         reuse=reuse)
        net = fire_module(net, 64, 256, name='fire8', **conv_args_fm)
        net = max_pool(net, name='maxpool8', **pool_args)
        net = bottleneck_simple(net, 64, 256, name='fire9', **conv_args_fm)
        net = batch_norm(net,
                         activation_fn=tf.nn.relu,
                         name='fire9_bn',
                         is_training=is_training,
                         reuse=reuse)
        # Reversed avg and conv layers per 'Network in Network'
        net = dropout(net,
                      drop_p=1 - dropout_keep_prob,
                      name='dropout6',
                      **common_args)
        net = conv2d(net,
                     num_classes,
                     filter_size=(1, 1),
                     name='conv10',
                     **conv_args_fm)
        logits = global_avg_pool(net, name='logits', **pool_args)
        predictions = softmax(logits, name='predictions', **common_args)
        return end_points(is_training)
Exemple #2
0
def test_delayed_update_moving_vars():
  with tf.Session() as sess:
    epsilon = 1e-5
    height, width = 3, 3
    image_shape = (10, height, width, 3)
    image_values = np.random.rand(*image_shape)
    expected_mean = np.mean(image_values, axis=(0, 1, 2))
    expected_inv_std = 1.0 / np.sqrt(np.var(image_values, axis=(0, 1, 2)) + epsilon)
    images = tf.constant(image_values, shape=image_shape, dtype=tf.float32)
    decay = 0.1
    output = batch_norm(images, True, None, decay=decay, epsilon=epsilon, name="BatchNorm")
    update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
    # updates_ops are added to UPDATE_OPS collection.
    assert len(update_ops) == 2
    with tf.control_dependencies(update_ops):
      barrier = tf.no_op(name='barrier')
    output = control_flow_ops.with_dependencies([barrier], output)
    # Initialize all variables
    sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])
    moving_mean = tf.contrib.framework.get_variables('BatchNorm/moving_mean')[0]
    moving_inv_std = tf.contrib.framework.get_variables('BatchNorm/moving_inv_std')[0]
    mean, inv_std = sess.run([moving_mean, moving_inv_std])
    # After initialization moving_mean == 0 and moving_variance == 1.
    assert_array_almost_equal(mean, [0] * 3)
    assert_array_almost_equal(inv_std, [1] * 3)
    for _ in range(10):
      sess.run([output])
    mean = moving_mean.eval()
    inv_std = moving_inv_std.eval()
    # After 10 updates with decay 0.1 moving_mean == expected_mean and
    # moving_inv_std == expected_inv_std.
    assert_array_almost_equal(mean, expected_mean, decimal=4)
    assert_array_almost_equal(inv_std, expected_inv_std, decimal=4)
Exemple #3
0
def test_eval_moving_vars():
  height, width = 3, 3
  with tf.Session() as sess:
    image_shape = (10, height, width, 3)
    image_values = np.random.rand(*image_shape)
    images = tf.constant(image_values, shape=image_shape, dtype=tf.float32)
    output = batch_norm(images, False, None, decay=0.1, name='BatchNorm')
    assert len(tf.get_collection(tf.GraphKeys.UPDATE_OPS)) == 0
    # Initialize all variables
    sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])
    moving_mean = tf.contrib.framework.get_variables('BatchNorm/moving_mean')[0]
    moving_inv_std = tf.contrib.framework.get_variables('BatchNorm/moving_inv_std')[0]
    mean, inv_std = sess.run([moving_mean, moving_inv_std])
    # After initialization moving_mean == 0 and moving_variance == 1.
    assert_array_almost_equal(mean, [0] * 3)
    assert_array_almost_equal(inv_std, [1] * 3)
    # Simulate assigment from saver restore.
    expected_moving_mean = [0.1] * 3  # could be any number
    expected_moving_inv_std = [0.5] * 3
    init_assigns = [
        tf.assign(moving_mean, expected_moving_mean),
        tf.assign(moving_inv_std, expected_moving_inv_std)
    ]
    sess.run(init_assigns)
    for _ in range(10):
      sess.run([output], {images: np.random.rand(*image_shape)})
    mean = moving_mean.eval()
    inv_std = moving_inv_std.eval()
    # Although we feed different images, the moving_mean and moving_variance
    # shouldn't change.
    assert_array_almost_equal(mean, expected_moving_mean)
    assert_array_almost_equal(inv_std, expected_moving_inv_std)
Exemple #4
0
def generator(z, is_training, reuse, n_hid=500, isize=28 * 28, use_bn=False):
    fc = dense(z, n_hid, is_training, reuse, w_regularizer=None, name='fc1')
    if use_bn:
        fc = tf.nn.relu(
            batch_norm(fc, is_training=is_training, reuse=reuse,
                       name='fc1/bn'))
    else:
        fc = tf.nn.relu(hid, name='fc1/prelu')
    fc = dense(fc, n_hid, is_training, reuse, w_regularizer=None, name='fc2')
    if use_bn:
        fc = tf.nn.relu(
            batch_norm(fc, is_training=is_training, reuse=reuse,
                       name='fc2/bn'))
    else:
        fc = rtf.nn.elu(fc, name='fc2/prelu')
    out = tf.nn.sigmoid(
        dense(fc, isize, is_training, reuse, w_regularizer=None, name='g_out'))
    return out
Exemple #5
0
def test_delayed_update_moving_vars_and_output():
    with tf.Session() as sess:
        height, width = 3, 3
        image_shape = (10, height, width, 3)
        image_values = np.random.rand(*image_shape)
        images_mean = np.mean(image_values, axis=(0, 1, 2))
        images_var = np.var(image_values, axis=(0, 1, 2))
        images = tf.constant(image_values, shape=image_shape, dtype=tf.float32)
        decay = 0.8
        epsilon = 1e-5
        output_s = batch_norm(images,
                              is_training=True,
                              scale=False,
                              reuse=None,
                              decay=decay,
                              fused=False,
                              epsilon=epsilon,
                              name='BatchNorm')
        update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
        # updates_ops are added to UPDATE_OPS collection.
        assert len(update_ops) == 2
        with tf.control_dependencies(update_ops):
            barrier = tf.no_op(name='barrier')
        output_s = control_flow_ops.with_dependencies([barrier], output_s)
        sess.run(tf.global_variables_initializer())

        moving_mean = tf.contrib.framework.get_variables(
            'BatchNorm/moving_mean')[0]
        moving_variance = tf.contrib.framework.get_variables(
            'BatchNorm/moving_variance')[0]
        mean, variance = sess.run([moving_mean, moving_variance])
        # After initialization moving_mean == 0 and moving_variance == 1.
        assert_array_almost_equal(mean, [0] * 3)
        assert_array_almost_equal(variance, [1] * 3)

        # Feed in the same batch of images 10 times
        n_times = 10
        expected_mean = np.array([0.] * 3)
        expected_var = np.array([1.] * 3)
        expected_output = (image_values - images_mean) / \
            np.sqrt(images_var + epsilon)
        for _ in range(n_times):
            output = sess.run(output_s)
            mean, variance = sess.run([moving_mean, moving_variance])
            expected_mean = expected_mean * decay + images_mean * (1 - decay)
            expected_var = expected_var * decay + images_var * (1 - decay)
            assert_array_almost_equal(output, expected_output, decimal=4)
            assert_array_almost_equal(mean, expected_mean, decimal=4)
            assert_array_almost_equal(variance, expected_var, decimal=4)
Exemple #6
0
def test_forced_update_moving_vars_and_output():
    tf.reset_default_graph()
    with tf.Session() as sess:
        height, width = 3, 3
        image_shape = (10, height, width, 3)
        image_values = np.random.rand(*image_shape)
        images_mean = np.mean(image_values, axis=(0, 1, 2))
        images_var = np.var(image_values, axis=(0, 1, 2))
        images = tf.constant(image_values, shape=image_shape, dtype=tf.float32)
        decay = 0.8
        epsilon = 1e-5
        images_inv_std = 1.0 / np.sqrt(images_var + epsilon)
        output_s = batch_norm(images,
                              True,
                              None,
                              decay=decay,
                              epsilon=epsilon,
                              updates_collections=None,
                              name="BatchNorm")
        sess.run([
            tf.global_variables_initializer(),
            tf.local_variables_initializer()
        ])

        moving_mean = tf.contrib.framework.get_variables(
            'BatchNorm/moving_mean')[0]
        moving_inv_std = tf.contrib.framework.get_variables(
            'BatchNorm/moving_inv_std')[0]
        mean, inv_std = sess.run([moving_mean, moving_inv_std])
        # After initialization moving_mean == 0 and moving_variance == 1.
        assert_array_almost_equal(mean, [0] * 3)
        assert_array_almost_equal(inv_std, [1] * 3)

        # Feed in the same batch of images 10 times
        n_times = 10
        expected_mean = np.array([0.] * 3)
        expected_inv_std = np.array([1.] * 3)
        expected_output = (image_values - images_mean) * images_inv_std
        for _ in range(n_times):
            output = sess.run(output_s)
            mean, inv_std = sess.run([moving_mean, moving_inv_std])
            expected_mean = expected_mean * decay + images_mean * (1 - decay)
            expected_inv_std = expected_inv_std * decay + images_inv_std * (
                1 - decay)
            assert_array_almost_equal(output, expected_output, decimal=4)
            assert_array_almost_equal(mean, expected_mean, decimal=4)
            assert_array_almost_equal(inv_std, expected_inv_std, decimal=4)
Exemple #7
0
def test_delayed_update_moving_vars():
    with tf.Session() as sess:
        height, width = 3, 3
        image_shape = (10, height, width, 3)
        image_values = np.random.rand(*image_shape)
        expected_mean = np.mean(image_values, axis=(0, 1, 2))
        expected_var = np.var(image_values, axis=(0, 1, 2))
        images = tf.constant(image_values, shape=image_shape, dtype=tf.float32)
        decay = 0.1
        epsilon = 1e-5
        output = batch_norm(images,
                            is_training=True,
                            scale=False,
                            reuse=None,
                            fused=False,
                            decay=decay,
                            epsilon=epsilon,
                            name='BatchNorm')
        update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
        # updates_ops are added to UPDATE_OPS collection.
        assert len(update_ops) == 2
        with tf.control_dependencies(update_ops):
            barrier = tf.no_op(name='barrier')
        output = control_flow_ops.with_dependencies([barrier], output)
        # Initialize all variables
        sess.run(tf.global_variables_initializer())
        moving_mean = tf.contrib.framework.get_variables(
            'BatchNorm/moving_mean')[0]
        moving_variance = tf.contrib.framework.get_variables(
            'BatchNorm/moving_variance')[0]
        mean, variance = sess.run([moving_mean, moving_variance])
        # After initialization moving_mean == 0 and moving_variance == 1.
        assert_array_almost_equal(mean, [0] * 3)
        assert_array_almost_equal(variance, [1] * 3)
        for _ in range(10):
            sess.run([output])
        mean = moving_mean.eval()
        variance = moving_variance.eval()
        # After 10 updates with decay 0.1 moving_mean == expected_mean and
        # moving_variance == expected_var.
        assert_array_almost_equal(mean, expected_mean, decimal=4)
        assert_array_almost_equal(variance, expected_var, decimal=4)
Exemple #8
0
def test_forced_update_moving_vars_and_output():
    with tf.Session() as sess:
        height, width = 3, 3
        image_shape = (10, height, width, 3)
        image_values = np.random.rand(*image_shape)
        images_mean = np.mean(image_values, axis=(0, 1, 2))
        images_var = np.var(image_values, axis=(0, 1, 2))
        images = tf.constant(image_values, shape=image_shape, dtype=tf.float32)
        decay = 0.8
        epsilon = 1e-5
        output_s = batch_norm(images,
                              is_training=True,
                              reuse=None,
                              decay=decay,
                              epsilon=epsilon,
                              updates_collections=None,
                              name='BatchNorm')
        sess.run(tf.global_variables_initializer())

        moving_mean = tf.contrib.framework.get_variables(
            'BatchNorm/moving_mean')[0]
        moving_variance = tf.contrib.framework.get_variables(
            'BatchNorm/moving_variance')[0]
        mean, variance = sess.run([moving_mean, moving_variance])
        # After initialization moving_mean == 0 and moving_variance == 1.
        assert_array_almost_equal(mean, [0] * 3)
        assert_array_almost_equal(variance, [1] * 3)

        # Feed in the same batch of images 10 times
        n_times = 10
        expected_mean = np.array([0.] * 3)
        expected_var = np.array([1.] * 3)
        expected_output = (image_values - images_mean) / np.sqrt(images_var +
                                                                 epsilon)
        for _ in xrange(n_times):
            output = sess.run(output_s)
            mean, variance = sess.run([moving_mean, moving_variance])
            expected_mean = expected_mean * decay + images_mean * (1 - decay)
            expected_var = expected_var * decay + images_var * (1 - decay)
            assert_array_almost_equal(output, expected_output, decimal=4)
            assert_array_almost_equal(mean, expected_mean, decimal=4)
            assert_array_almost_equal(variance, expected_var, decimal=4)
Exemple #9
0
def bottleneck_simple(inputs,
                      squeeze_depth,
                      expand_depth,
                      name=None,
                      **kwargs):
    """Bottleneck residual unit variant with BN before convolutions.
    Note: inputs depth same as outputh depth

    When putting together two consecutive ResNet blocks that use this unit, one
    should use stride = 2 in the last unit of the first block.

    Args:
      inputs: A tensor of size [batch, height, width, channels].
      squeeze_depth: The depth of the squeeze layers.
      exapnd_depth: The depth of the exapnd layers.
      stride: The ResNet unit's stride. Determines the amount of downsampling of
        the units output compared to its input.
      name: Optional variable_scope.

    Returns:
      The ResNet unit's output.
    """
    is_training = kwargs.get('is_training')
    reuse = kwargs.get('reuse')
    depth_in = util.last_dimension(inputs.get_shape(), min_rank=4)
    assert depth_in == 2 * expand_depth, 'input depth should be twice of exapnd_depth'
    with tf.variable_scope(name, 'bottleneck_simple', [inputs]):
        preact = batch_norm(inputs,
                            name='preact',
                            is_training=is_training,
                            reuse=reuse)
        preact = prelu(preact, reuse, name='prelu_start')
        residual = squeeze(preact, squeeze_depth, **kwargs)
        residual = expand(residual, expand_depth, **kwargs)

        output = prelu(inputs + residual, reuse, name='prelu_residual')
        return output
def test_forced_update_moving_vars():
    with tf.Session() as sess:
        epsilon = 1e-5
        height, width = 3, 3
        image_shape = (10, height, width, 3)
        image_values = np.random.rand(*image_shape)
        expected_mean = np.mean(image_values, axis=(0, 1, 2))
        expected_inv_std = 1.0 / np.sqrt(
            np.var(image_values, axis=(0, 1, 2)) + epsilon)
        images = tf.constant(image_values, shape=image_shape, dtype=tf.float32)
        decay = 0.1
        output = batch_norm(images,
                            True,
                            None,
                            decay=decay,
                            epsilon=epsilon,
                            name="BatchNorm",
                            updates_collections=None)
        # Initialize all variables
        sess.run(tf.global_variables_initializer())
        moving_mean = tf.contrib.framework.get_variables(
            'BatchNorm/moving_mean')[0]
        moving_inv_std = tf.contrib.framework.get_variables(
            'BatchNorm/moving_inv_std')[0]
        mean, inv_std = sess.run([moving_mean, moving_inv_std])
        # After initialization moving_mean == 0 and moving_variance == 1.
        assert_array_almost_equal(mean, [0] * 3)
        assert_array_almost_equal(inv_std, [1] * 3)
        for _ in range(10):
            sess.run([output])
        mean = moving_mean.eval()
        inv_std = moving_inv_std.eval()
        # After 10 updates with decay 0.1 moving_mean == expected_mean and
        # moving_inv_std == expected_inv_std.
        assert_array_almost_equal(mean, expected_mean)
        assert_array_almost_equal(inv_std, expected_inv_std)
Exemple #11
0
def bottleneck(inputs,
               depth,
               squeeze_depth,
               expand_depth,
               stride,
               rate=1,
               name=None,
               **kwargs):
    """Bottleneck residual unit variant with BN before convolutions.

    This is the full preactivation residual unit variant proposed in [2]. See
    Fig. 1(b) of [2] for its definition. Note that we use here the bottleneck
    variant which has an extra bottleneck layer.

    When putting together two consecutive ResNet blocks that use this unit, one
    should use stride = 2 in the last unit of the first block.

    Args:
      inputs: A tensor of size [batch, height, width, channels].
      depth: The depth of the ResNet unit output.
      squeeze_depth: The depth of the squeeze layers.
      exapnd_depth: The depth of the exapnd layers.
      stride: The ResNet unit's stride. Determines the amount of downsampling of
        the units output compared to its input.
      rate: An integer, rate for atrous convolution.
      outputs_collections: Collection to add the ResNet unit output.
      name: Optional variable_scope.

    Returns:
      The ResNet unit's output.
    """
    is_training = kwargs.get('is_training')
    reuse = kwargs.get('reuse')
    with tf.variable_scope(name, 'bottleneck_v2', [inputs]):
        depth_in = util.last_dimension(inputs.get_shape(), min_rank=4)
        preact = batch_norm(inputs,
                            activation_fn=tf.nn.relu,
                            name='preact',
                            is_training=is_training,
                            reuse=reuse)
        if depth == depth_in:
            shortcut = inputs
        else:
            shortcut = conv2d(preact,
                              depth,
                              is_training,
                              reuse,
                              filter_size=(1, 1),
                              stride=(stride, stride),
                              batch_norm=None,
                              activation=None,
                              name='shortcut')

        residual = fire_module(preact,
                               squeeze_depth,
                               expand_depth,
                               name='fire2',
                               **kwargs)
        residual = conv2d(residual,
                          depth,
                          is_training,
                          reuse,
                          filter_size=(1, 1),
                          stride=(1, 1),
                          batch_norm=None,
                          activation=None,
                          name='conv3')

        output = tf.nn.relu(shortcut + residual)
        return output
Exemple #12
0
def resnet_v1(inputs,
              is_training,
              reuse,
              blocks,
              num_classes=None,
              global_pool=True,
              output_stride=None,
              include_root_block=True,
              name=None):
    """Generator for v2 (preactivation) ResNet models.

    This function generates a family of ResNet v2 models. See the resnet_v2_*()
    methods for specific model instantiations, obtained by selecting different
    block instantiations that produce ResNets of various depths.

    Training for image classification on Imagenet is usually done with [224, 224]
    inputs, resulting in [7, 7] feature maps at the output of the last ResNet
    block for the ResNets defined in [1] that have nominal stride equal to 32.
    However, for dense prediction tasks we advise that one uses inputs with
    spatial dimensions that are multiples of 32 plus 1, e.g., [321, 321]. In
    this case the feature maps at the ResNet output will have spatial shape
    [(height - 1) / output_stride + 1, (width - 1) / output_stride + 1]
    and corners exactly aligned with the input image corners, which greatly
    facilitates alignment of the features to the image. Using as input [225, 225]
    images results in [8, 8] feature maps at the output of the last ResNet block.

    For dense prediction tasks, the ResNet needs to run in fully-convolutional
    (FCN) mode and global_pool needs to be set to False. The ResNets in [1, 2] all
    have nominal stride equal to 32 and a good choice in FCN mode is to use
    output_stride=16 in order to increase the density of the computed features at
    small computational and memory overhead, cf. http://arxiv.org/abs/1606.00915.

    Args:
      inputs: A tensor of size [batch, height_in, width_in, channels].
      blocks: A list of length equal to the number of ResNet blocks. Each element
        is a resnet_utils.Block object describing the units in the block.
      num_classes: Number of predicted classes for classification tasks. If None
        we return the features before the logit layer.
      is_training: whether is training or not.
      global_pool: If True, we perform global average pooling before computing the
        logits. Set to True for image classification, False for dense prediction.
      output_stride: If None, then the output will be computed at the nominal
        network stride. If output_stride is not None, it specifies the requested
        ratio of input to output spatial resolution.
      include_root_block: If True, include the initial convolution followed by
        max-pooling, if False excludes it. If excluded, `inputs` should be the
        results of an activation-less convolution.
      reuse: whether or not the network and its variables should be reused. To be
        able to reuse 'scope' must be given.
      name: Optional variable_scope.


    Returns:
      net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
        If global_pool is False, then height_out and width_out are reduced by a
        factor of output_stride compared to the respective height_in and width_in,
        else both height_out and width_out equal one. If num_classes is None, then
        net is the output of the last ResNet block, potentially after global
        average pooling. If num_classes is not None, net contains the pre-softmax
        activations.
      end_points: A dictionary from components of the network to the corresponding
        activation.

    Raises:
      ValueError: If the target output_stride is not valid.
    """
    common_args = common_layer_args(is_training, reuse)
    conv_args = make_args(batch_norm=True,
                          activation=prelu,
                          w_init=initz.he_normal(scale=1),
                          untie_biases=False,
                          **common_args)
    logits_args = make_args(activation=None,
                            w_init=initz.he_normal(scale=1),
                            **common_args)
    pred_args = make_args(activation=prelu,
                          w_init=initz.he_normal(scale=1),
                          **common_args)
    pool_args = make_args(padding='SAME', **common_args)

    with tf.variable_scope(name, 'resnet_v2', [inputs], reuse=reuse):
        net = inputs
        if include_root_block:
            if output_stride is not None:
                if output_stride % 4 != 0:
                    raise ValueError(
                        'The output_stride needs to be a multiple of 4.')
                output_stride /= 4
            # We do not include batch normalization or activation functions in
            # conv1 because the first ResNet unit will perform these. Cf.
            # Appendix of [2].
            net = resnet_utils.conv2d_same(net,
                                           64,
                                           7,
                                           stride=2,
                                           name='conv1',
                                           **common_args)
            net = max_pool(net, name='pool1', **pool_args)
        net = resnet_utils.stack_blocks_dense(net, blocks, output_stride,
                                              **conv_args)
        # This is needed because the pre-activation variant does not have batch
        # normalization or activation functions in the residual unit output. See
        # Appendix of [2].
        net = batch_norm(net,
                         activation=tf.nn.relu,
                         name='postnorm',
                         is_training=is_training,
                         reuse=reuse)
        if global_pool:
            # Global average pooling.
            net = tf.reduce_mean(net, [1, 2], name='pool5', keep_dims=True)
        if num_classes is not None:
            net = conv2d(net,
                         num_classes,
                         filter_size=(1, 1),
                         name='logits',
                         **logits_args)
        if num_classes is not None:
            predictions = softmax(net, name='predictions', **pred_args)

        return end_points(is_training)
Exemple #13
0
def bottleneck_se(inputs,
                  depth,
                  depth_bottleneck,
                  stride,
                  rate=1,
                  name=None,
                  **kwargs):
    """SE Bottleneck residual unit variant with BN before convolutions.

  This is the full preactivation residual unit variant proposed in [2]. See
  Fig. 1(b) of [2] for its definition. Note that we use here the bottleneck
  variant which has an extra bottleneck layer.

  When putting together two consecutive ResNet blocks that use this unit, one
  should use stride = 2 in the last unit of the first block.

  Args:
    inputs: A tensor of size [batch, height, width, channels].
    depth: The depth of the ResNet unit output.
    depth_bottleneck: The depth of the bottleneck layers.
    stride: The ResNet unit's stride. Determines the amount of downsampling of
      the units output compared to its input.
    rate: An integer, rate for atrous convolution.
    outputs_collections: Collection to add the ResNet unit output.
    name: Optional variable_scope.

  Returns:
    The ResNet unit's output.
  """
    is_training = kwargs.get('is_training')
    reuse = kwargs.get('reuse')
    with tf.variable_scope(name, 'bottleneck_se', [inputs]):
        depth_in = util.last_dimension(inputs.get_shape(), min_rank=4)
        preact = batch_norm(inputs,
                            activation_fn=tf.nn.relu,
                            name='preact',
                            is_training=is_training,
                            reuse=reuse)
        if depth * 4 == depth_in:
            shortcut = subsample(preact, stride, 'shortcut')
        else:
            shortcut = conv2d(preact,
                              depth * 4,
                              is_training,
                              reuse,
                              filter_size=(1, 1),
                              stride=(stride, stride),
                              batch_norm=None,
                              activation=None,
                              name='shortcut')

        residual = conv2d(preact,
                          depth,
                          filter_size=(1, 1),
                          stride=(1, 1),
                          name='conv1',
                          **kwargs)
        residual = conv2d(residual,
                          depth,
                          filter_size=(3, 3),
                          stride=(stride, stride),
                          name='conv2',
                          **kwargs)
        residual = conv2d(residual,
                          depth * 4,
                          is_training,
                          reuse,
                          filter_size=(1, 1),
                          stride=(1, 1),
                          batch_norm=None,
                          activation=None,
                          name='conv3')

        squeeze = global_avg_pool(residual, name='se_global_avg_pool')
        squeeze = fully_connected(squeeze,
                                  depth // 4,
                                  is_training,
                                  reuse,
                                  name='fc1')
        squeeze = fully_connected(squeeze,
                                  depth * 4,
                                  is_training,
                                  reuse,
                                  name='fc2')
        squeeze = tf.nn.sigmoid(squeeze, name='se_fc_sigmoid')
        residual = residual * tf.reshape(squeeze, [-1, 1, 1, depth * 4])
        return residual + shortcut