def _build_base(self):
    with tf.variable_scope(self._scope, self._scope):
      net = resnet_utils.conv2d_same(self._image, 64, 7, stride=2, scope='conv1')
      net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
      net = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='pool1')

    return net
Example #2
0
    def build_base(self):
        with tf.variable_scope(self.scope, self.scope, reuse=tf.AUTO_REUSE,):
            net = resnet_utils.conv2d_same(self.image, 64, 7, stride=2, scope='conv1')
            net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
            net = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='pool1')

        return net
Example #3
0
def bottleneck(inputs,
               depth,
               depth_bottleneck,
               stride,
               rate=1,
               outputs_collections=None,
               scope=None):
    """Bottleneck residual unit variant with BN after convolutions.

  This is the original residual unit proposed in [1]. See Fig. 1(a) 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.
    scope: Optional variable_scope.

  Returns:
    The ResNet unit's output.
  """
    with variable_scope.variable_scope(scope, 'bottleneck_v1', [inputs]) as sc:
        depth_in = utils.last_dimension(inputs.get_shape(), min_rank=4)
        if depth == depth_in:
            shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')
        else:
            shortcut = layers.conv2d(inputs,
                                     depth, [1, 1],
                                     stride=stride,
                                     activation_fn=None,
                                     scope='shortcut')

        residual = layers.conv2d(inputs,
                                 depth_bottleneck, [1, 1],
                                 stride=1,
                                 scope='conv1')
        residual = resnet_utils.conv2d_same(residual,
                                            depth_bottleneck,
                                            3,
                                            stride,
                                            rate=rate,
                                            scope='conv2')
        residual = layers.conv2d(residual,
                                 depth, [1, 1],
                                 stride=1,
                                 activation_fn=None,
                                 scope='conv3')

        output = nn_ops.relu(shortcut + residual)

        return utils.collect_named_outputs(outputs_collections, sc.name,
                                           output)
Example #4
0
def bottleneck(inputs,
               depth,
               depth_bottleneck,
               stride,
               rate=1,
               outputs_collections=None,
               scope=None):
  """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.
    scope: Optional variable_scope.

  Returns:
    The ResNet unit's output.
  """
  with variable_scope.variable_scope(scope, 'bottleneck_v2', [inputs]) as sc:
    depth_in = utils.last_dimension(inputs.get_shape(), min_rank=4)
    preact = layers.batch_norm(
        inputs, activation_fn=nn_ops.relu, scope='preact')
    if depth == depth_in:
      shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')
    else:
      shortcut = layers_lib.conv2d(
          preact,
          depth, [1, 1],
          stride=stride,
          normalizer_fn=None,
          activation_fn=None,
          scope='shortcut')

    residual = layers_lib.conv2d(
        preact, depth_bottleneck, [1, 1], stride=1, scope='conv1')
    residual = resnet_utils.conv2d_same(
        residual, depth_bottleneck, 3, stride, rate=rate, scope='conv2')
    residual = layers_lib.conv2d(
        residual,
        depth, [1, 1],
        stride=1,
        normalizer_fn=None,
        activation_fn=None,
        scope='conv3')

    output = shortcut + residual

    return utils.collect_named_outputs(outputs_collections, sc.name, output)
Example #5
0
def atrous_spatial_pyramid_pooling(inputs, output_stride, batch_norm_decay, is_training, depth=256):
  """Atrous Spatial Pyramid Pooling.

  Args:
    inputs: A tensor of size [batch, height, width, channels].
    output_stride: The ResNet unit's stride. Determines the rates for atrous convolution.
      the rates are (6, 12, 18) when the stride is 16, and doubled when 8.
    batch_norm_decay: The moving average decay when estimating layer activation
      statistics in batch normalization.
    is_training: A boolean denoting whether the input is for training.
    depth: The depth of the ResNet unit output.

  Returns:
    The atrous spatial pyramid pooling output.
  """
  with tf.variable_scope("aspp"):
    if output_stride not in [8, 16]:
      raise ValueError('output_stride must be either 8 or 16.')

    atrous_rates = [6, 12, 18]
    if output_stride == 8:
      atrous_rates = [2*rate for rate in atrous_rates]

    with tf.contrib.slim.arg_scope(resnet_v2.resnet_arg_scope(batch_norm_decay=batch_norm_decay)):
      with arg_scope([layers.batch_norm], is_training=is_training):
        inputs_size = tf.shape(inputs)[1:3]
        # (a) one 1×1 convolution and three 3×3 convolutions with rates = (6, 12, 18) when output stride = 16.
        # the rates are doubled when output stride = 8.
        conv_1x1 = layers_lib.conv2d(inputs, depth, [1, 1], stride=1, scope="conv_1x1")
        conv_3x3_1 = resnet_utils.conv2d_same(inputs, depth, 3, stride=1, rate=atrous_rates[0], scope='conv_3x3_1')
        conv_3x3_2 = resnet_utils.conv2d_same(inputs, depth, 3, stride=1, rate=atrous_rates[1], scope='conv_3x3_2')
        conv_3x3_3 = resnet_utils.conv2d_same(inputs, depth, 3, stride=1, rate=atrous_rates[2], scope='conv_3x3_3')

        # (b) the image-level features
        with tf.variable_scope("image_level_features"):
          # global average pooling
          image_level_features = tf.reduce_mean(inputs, [1, 2], name='global_average_pooling', keepdims=True)
          # 1×1 convolution with 256 filters( and batch normalization)
          image_level_features = layers_lib.conv2d(image_level_features, depth, [1, 1], stride=1, scope='conv_1x1')
          # bilinearly upsample features
          image_level_features = tf.image.resize_bilinear(image_level_features, inputs_size, name='upsample')

        net = tf.concat([conv_1x1, conv_3x3_1, conv_3x3_2, conv_3x3_3, image_level_features], axis=3, name='concat')
        net = layers_lib.conv2d(net, depth, [1, 1], stride=1, scope='conv_1x1_concat')

        return net
  def build_base(self,conv):

    with tf.variable_scope(self._resnet_scope, self._resnet_scope):
      net = resnet_utils.conv2d_same(conv, 64, 7, stride=2, scope='conv1')
      net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
      net = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='pool1')

    return net
Example #7
0
def RRB(inputs, is_training=True, depth=512):
    """Refinement Residual Block.

      Args:
        inputs: A tensor of size [batch, height, width, channels].

      Returns:
         output.
      """
    conv_1x1 = layers_lib.conv2d(inputs, depth, [1, 1], stride=1)
    conv_3x3_1 = resnet_utils.conv2d_same(conv_1x1, depth, 3, stride=1)
    batch_norm = tf.layers.batch_normalization(conv_3x3_1,
                                               training=is_training)
    relu1 = tf.nn.relu(batch_norm)
    conv_3x3_2 = resnet_utils.conv2d_same(relu1, depth, 3, stride=1)
    sum = tf.add_n([conv_1x1, conv_3x3_2])
    relu2 = tf.nn.relu(sum)
    return relu2
 def uncompressed_func():
     nonlocal uncompressed_net
     if uncompressed_net is None:  #need this as irritatingly the tf.case() calls it twice
         uncompressed_net = resnet_utils.conv2d_same(
             inputs,
             num_output_channels,
             kernel_size,
             stride=stride,
             scope=layer_name)
     return uncompressed_net
Example #9
0
    def build_base(self):
        c = np.zeros((3, 5, 5))
        c[0] = [[-1, 2, -2, 2, -1], [2, -6, 8, -6, 2], [-2, 8, -12, 8, -2],
                [2, -6, 8, -6, 2], [-1, 2, -2, 2, -1]]
        c[0] = c[0] / 12

        c[1] = [[0, 0, 0, 0, 0], [0, -1, 2, -1, 0], [0, 0, 2, -4, 2, 0],
                [0, -1, 2, -1, 0], [0, 0, 0, 0, 0]]
        c[1] /= 4

        #c[2][2][1]=1
        #c[2][2][2]=-2
        #c[2][2][3]=1
        #c[2]=c[2]/2

        c[2] = [[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, -2, 0, 0],
                [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]]
        c[2] /= 2

        Wcnn = np.zeros((5, 5, 3, 3))
        for i in xrange(3):
            #k=i%10+1
            #Wcnn[i]=[c[3*k-3],c[3*k-2],c[3*k-1]]
            Wcnn[:, :, 0, i] = c[i]
            Wcnn[:, :, 1, i] = c[i]
            Wcnn[:, :, 2, i] = c[i]
        with tf.variable_scope('noise'):
            #kernel = tf.get_variable('weights',
            #shape=[5, 5, 3, 3],
            #initializer=tf.constant_initializer(c))
            conv = tf.nn.conv2d(self._image,
                                Wcnn, [1, 1, 1, 1],
                                padding='SAME',
                                name='srm')
        self._layers['noise'] = conv
        #with tf.variable_scope('noise'):
        ##kernel = tf.get_variable('weights',
        #shape=[5, 5, 3, 3],
        #initializer=tf.constant_initializer(Wcnn))
        #conv = tf.nn.conv2d(self.noise, Wcnn, [1, 1, 1, 1], padding='SAME',name='srm')
        #conv = tf.nn.conv2d(self.noise, kernel, [1, 1, 1, 1], padding='SAME',name='srm')
        #srm_conv = tf.nn.tanh(conv, name='tanh')
        with tf.variable_scope(self._resnet_scope, self._resnet_scope):
            net = resnet_utils.conv2d_same(conv,
                                           64,
                                           7,
                                           stride=2,
                                           scope='conv1')
            net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
            net = slim.max_pool2d(net, [3, 3],
                                  stride=2,
                                  padding='VALID',
                                  scope='pool1')

        return net
  def build_base(self, ver='', init=None):
    with tf.variable_scope(self._resnet_scope, self._resnet_scope):
      if(ver == 'n'):
          def truncate_2(x):
              neg = ((x + 2) + abs(x + 2)) / 2 - 2
              return -(2 - neg + abs(2 - neg)) / 2 + 2

          # Main network
          # Layer SRM
          net = slim.conv2d(self._image, 3, [5, 5], trainable=True, weights_initializer=init,
                            activation_fn=None, padding='SAME', stride=1, scope='srm')
          net = truncate_2(net)
          net = resnet_utils.conv2d_same(net, 64, 7, stride=2, scope='conv1'+ver)
          net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
          net = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='pool1'+ver)
      else:
          net = resnet_utils.conv2d_same(self._image, 64, 7, stride=2, scope='conv1'+ver)
          net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
          net = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='pool1'+ver)

    return net
def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None):
    with tf.variable_scope(scope, 'bottleneck_v1', [inputs]) as sc:
        depth_in = slim.utils.last_dimension(inputs.get_shape(), min_rank=4)
        if depth == depth_in:
            shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')
        else:
            shortcut = slim.conv2d(inputs, depth, [1, 1], stride=stride, activation_fn=None, scope='shortcut')
        residual = slim.conv2d(inputs, depth_bottleneck, [1, 1], stride=1, scope='conv1')
        residual = resnet_utils.conv2d_same(residual, depth_bottleneck, 3, stride, rate=rate, scope='conv2')
        residual = slim.conv2d(residual, depth, [1, 1], stride=1, activation_fn=None, scope='conv3')
        output = tf.nn.relu(shortcut + residual)

    return slim.utils.collect_named_outputs(outputs_collections, sc.original_name_scope, output)
    def _build_base(self, reuse=None):
        with tf.variable_scope(self._scope, self._scope) as scope:
            if (reuse == True):
                scope.reuse_variables()
                net = resnet_utils.conv2d_same(self._image_large,
                                               64,
                                               7,
                                               stride=2,
                                               scope='conv1')
            else:
                net = resnet_utils.conv2d_same(self._image_small,
                                               64,
                                               7,
                                               stride=2,
                                               scope='conv1')
            net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
            net = slim.max_pool2d(net, [3, 3],
                                  stride=2,
                                  padding='VALID',
                                  scope='pool1')

        return net
Example #13
0
def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None):
    with tf.variable_scope(scope, 'bottleneck_v1', [inputs]) as sc:
        depth_in = slim.utils.last_dimension(inputs.get_shape(), min_rank=4)
        if depth == depth_in:
            shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')
        else:
            shortcut = slim.conv2d(inputs, depth, [1, 1], stride=stride, activation_fn=None, scope='shortcut')
        residual = slim.conv2d(inputs, depth_bottleneck, [1, 1], stride=1, scope='conv1')
        residual = resnet_utils.conv2d_same(residual, depth_bottleneck, 3, stride, rate=rate, scope='conv2')
        residual = slim.conv2d(residual, depth, [1, 1], stride=1, activation_fn=None, scope='conv3')
        output = tf.nn.relu(shortcut + residual)

    return slim.utils.collect_named_outputs(outputs_collections, sc.original_name_scope, output)
Example #14
0
def resnet_v1(inputs,
              blocks,
              num_classes=None,
              is_training=True,
              global_pool=True,
              output_stride=None,
              include_root_block=True,
              reuse=None,
              scope=None):
    with variable_scope.variable_scope(scope,
                                       'resnet_v1', [inputs],
                                       reuse=reuse) as sc:
        end_points_collection = sc.original_name_scope + '_end_points'
        with arg_scope([layers.conv2d, naive, resnet_utils.stack_blocks_dense],
                       outputs_collections=end_points_collection):
            with arg_scope([layers.batch_norm], is_training=is_training):
                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
                    net = resnet_utils.conv2d_same(net,
                                                   64,
                                                   7,
                                                   stride=2,
                                                   scope='conv1')
                    net = layers_lib.max_pool2d(net, [3, 3],
                                                stride=2,
                                                scope='pool1')
                net = resnet_utils.stack_blocks_dense(net, blocks,
                                                      output_stride)
                if global_pool:
                    # Global average pooling.
                    net = math_ops.reduce_mean(net, [1, 2],
                                               name='pool5',
                                               keep_dims=True)
                if num_classes is not None:
                    net = layers.conv2d(net,
                                        num_classes, [1, 1],
                                        activation_fn=None,
                                        normalizer_fn=None,
                                        scope='logits')
                end_points = utils.convert_collection_to_dict(
                    end_points_collection)
                if num_classes is not None:
                    end_points['predictions'] = layers_lib.softmax(
                        net, scope='predictions')
                return net, end_points
Example #15
0
 def _build_base_hm(self):
     with tf.variable_scope('hm/' + self._scope, 'hm/' + self._scope):
         net = resnet_utils.conv2d_same(self._image[..., 3:],
                                        64,
                                        7,
                                        stride=2,
                                        scope='conv1')
         net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
         net = slim.max_pool2d(net, [3, 3],
                               stride=2,
                               padding='VALID',
                               scope='pool1')
         self._layers['base_hm'] = net
     return net
Example #16
0
 def _build_base(self):
     with tf.variable_scope(self._scope, self._scope):
         net = resnet_utils.conv2d_same(self._image,
                                        64,
                                        7,
                                        stride=2,
                                        scope='conv1')
         # 只填充宽高两个维度,上下左右各填充一层
         net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
         net = slim.max_pool2d(net, [3, 3],
                               stride=2,
                               padding='VALID',
                               scope='pool1')
     return net
Example #17
0
    def encoder(self, x):
        with tf.variable_scope('encoder'):
            net = resnet_utils.conv2d_same(x, 64, 7, stride=2, scope='conv1')
            net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
            x = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='pool1')
            x_features_all, _ = resnet_v1.resnet_v1(x,
                                                self._blocks_encoder,
                                                global_pool=False,
                                                include_root_block=False,
                                                scope=self._resnet_scope)
            x_features_all = tf.reduce_mean(x_features_all, axis=[1, 2])
            x_features_labeled, x_features_unlabeled = tf.split(x_features_all, 2)

        x_features_tiled = tf.tile(x_features_unlabeled, [self._num_classes, 1])  # (100, 256) --> (2100, 256)
        x_features = tf.concat([x_features_labeled, x_features_tiled], 0) # (2100, 256) --> (2200, 256)
        return x_features
Example #18
0
def mobilenet_v1_base(inputs,
                      conv_defs,
                      starting_layer=0,
                      min_depth=8,
                      depth_multiplier=1.0,
                      output_stride=None,
                      reuse=None,
                      scope=None):
    # starting_layer 对于RPN为0,对于region classification 是12
    depth =lambda d:max(int(d*depth_multiplier),min_depth)
    end_points = {}
    if depth_multiplier <= 0:
        raise ValueError('depth_multiplier is not greater than zero.')

    with tf.variable_scope(scope,'MobilenetV1',[inputs],reuse=reuse):
        current_stride = 1
        rate = 1
        net = inputs
        for i, conv_def in enumerate(conv_defs):
            end_point_base = 'Conv2d_%d'%(i+starting_layer)
            if output_stride is not None and current_stride == output_stride:
                layer_stride = 1
                layer_rate = rate
                rate *= conv_def.stride
            else:
                layer_stride = conv_def.stride
                layer_rate = 1
                current_stride *= conv_def.stride

            if isinstance(conv_def,Conv):
                end_point = end_point_base
                net = resnet_utils.conv2d_same(net,depth(conv_def.depth),conv_def.kernel,
                                               stride=conv_def.stride,
                                               scope=end_point)
            elif isinstance(conv_def,DepthSepConv):
                end_point = end_point_base + '_depthwise'
                net = separable_conv2d_same(net,conv_def.kernel,
                                            stride=layer_stride,
                                            rate=layer_rate,
                                            scope=end_point)
                end_point = end_point_base + '_pointwise'
                net = slim.conv2d(net,depth(conv_def.depth),[1,1],
                                  stride=1,
                                  scope=end_point)
            else:
                raise ValueError('Unknown convolution type %s for layer %d'%(conv_def.ltype,i))
        return net
Example #19
0
    def build_base(self):
        c = np.zeros((3, 5, 5))
        c[0] = [[-1, 2, -2, 2, -1], [2, -6, 8, -6, 2], [-2, 8, -12, 8, -2],
                [2, -6, 8, -6, 2], [-1, 2, -2, 2, -1]]
        c[0] = c[0] / 12

        c[1][1][1] = -1
        c[1][1][2] = 2
        c[1][1][3] = -1
        c[1][2][1] = 2
        c[1][2][2] = -4
        c[1][2][3] = 2
        c[1][3][1] = -1
        c[1][3][2] = 2
        c[1][3][3] = -1
        c[1] = c[1] / 4

        c[2][1][2] = 1
        c[2][2][2] = -2
        c[2][3][2] = 1
        c[2] = c[2] / 2

        Wcnn = np.zeros((5, 5, 3, 3))
        for i in xrange(3):
            Wcnn[:, :, 0, i] = c[i]
            Wcnn[:, :, 1, i] = c[i]
            Wcnn[:, :, 2, i] = c[i]
        with tf.variable_scope('noise'):
            conv = tf.nn.conv2d(self._image,
                                Wcnn, [1, 1, 1, 1],
                                padding='SAME',
                                name='srm')
        self._layers['noise'] = conv
        with tf.variable_scope(self._resnet_scope, self._resnet_scope):
            net = resnet_utils.conv2d_same(conv,
                                           64,
                                           7,
                                           stride=2,
                                           scope='conv1')
            net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
            net = slim.max_pool2d(net, [3, 3],
                                  stride=2,
                                  padding='VALID',
                                  scope='pool1')

        return net
def bottleneck(inputs,
               depth,
               depth_bottleneck,
               stride,
               rate=1,
               outputs_collections=None,
               scope=None):
  with variable_scope.variable_scope(scope, 'bottleneck_v2', [inputs]) as sc:
    depth_in = utils.last_dimension(inputs.get_shape(), min_rank=4)
    preact = layers.batch_norm(
        inputs, activation_fn=nn_ops.relu, scope='preact')
    if depth == depth_in:
      shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')
    else:
      shortcut = layers_lib.conv2d(
          preact,
          depth, [1, 1],
          stride=stride,
          normalizer_fn=None,
          activation_fn=None,
          scope='shortcut')

    residual = preact
    residual = tf.layers.batch_normalization(residual)
    residual = tf.nn.relu(residual)
    residual = layers_lib.conv2d(
        residual, depth_bottleneck, [1, 1], stride=1, scope='conv1')
    residual = tf.layers.batch_normalization(residual)
    residual = tf.nn.relu(residual)
    residual = resnet_utils.conv2d_same(
        residual, depth_bottleneck, 3, stride, rate=rate, scope='conv2')
    residual = tf.layers.batch_normalization(residual)
    residual = tf.nn.relu(residual)
    residual = layers_lib.conv2d(
        residual,
        depth, [1, 1],
        stride=1,
        normalizer_fn=None,
        activation_fn=None,
        scope='conv3')

    output = shortcut + residual

    return utils.collect_named_outputs(outputs_collections, sc.name, output)
Example #21
0
def resnet50V2_reduced(inputs,
                       is_training=True,
                       output_stride=None,
                       include_root_block=True,
                       reuse=None,
                       scope=None):

    # These are the blocks for resnet 50
    blocks = [
        resnet_utils.Block('block1', bottleneck,
                           [(256, 64, 1)] * 2 + [(256, 64, 2)]),
        resnet_utils.Block('block2', bottleneck,
                           [(512, 128, 1)] * 3 + [(512, 128, 2)]),
        resnet_utils.Block('block3', bottleneck, [(1024, 256, 1)] * 5)
    ]

    # Initialize Model
    with tf.variable_scope(scope, 'resnet_v2_50', [inputs], reuse=reuse):
        with slim.arg_scope(
            [slim.conv2d, bottleneck, resnet_utils.stack_blocks_dense]):
            with slim.arg_scope([slim.batch_norm],
                                is_training=is_training) as scope:
                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
                    with slim.arg_scope([slim.conv2d],
                                        activation_fn=None,
                                        normalizer_fn=None):
                        net = resnet_utils.conv2d_same(net,
                                                       64,
                                                       7,
                                                       stride=2,
                                                       scope='conv1')
                    net = slim.max_pool2d(net, [3, 3], stride=2, scope='pool1')
                net = resnet_utils.stack_blocks_dense(net, blocks,
                                                      output_stride)
    with slim.arg_scope([slim.batch_norm], is_training=is_training) as scope:
        net = slim.batch_norm(net, activation_fn=tf.nn.relu, scope='postnorm')
    return net
Example #22
0
  def testConv2DSameOdd(self):
    n, n2 = 5, 3

    # Input image.
    x = create_test_input(1, n, n, 1)

    # Convolution kernel.
    w = create_test_input(1, 3, 3, 1)
    w = array_ops.reshape(w, [3, 3, 1, 1])

    variable_scope.get_variable('Conv/weights', initializer=w)
    variable_scope.get_variable('Conv/biases', initializer=array_ops.zeros([1]))
    variable_scope.get_variable_scope().reuse_variables()

    y1 = layers.conv2d(x, 1, [3, 3], stride=1, scope='Conv')
    y1_expected = math_ops.cast([[14, 28, 43, 58, 34],
                                 [28, 48, 66, 84, 46],
                                 [43, 66, 84, 102, 55],
                                 [58, 84, 102, 120, 64],
                                 [34, 46, 55, 64, 30]],
                                dtypes.float32)
    y1_expected = array_ops.reshape(y1_expected, [1, n, n, 1])

    y2 = resnet_utils.subsample(y1, 2)
    y2_expected = math_ops.cast([[14, 43, 34],
                                 [43, 84, 55],
                                 [34, 55, 30]],
                                dtypes.float32)
    y2_expected = array_ops.reshape(y2_expected, [1, n2, n2, 1])

    y3 = resnet_utils.conv2d_same(x, 1, 3, stride=2, scope='Conv')
    y3_expected = y2_expected

    y4 = layers.conv2d(x, 1, [3, 3], stride=2, scope='Conv')
    y4_expected = y2_expected

    with self.cached_session() as sess:
      sess.run(variables.global_variables_initializer())
      self.assertAllClose(y1.eval(), y1_expected.eval())
      self.assertAllClose(y2.eval(), y2_expected.eval())
      self.assertAllClose(y3.eval(), y3_expected.eval())
      self.assertAllClose(y4.eval(), y4_expected.eval())
Example #23
0
    def build_base(self):
        #with tf.variable_scope('noise'):
        ##kernel = tf.get_variable('weights',
        #shape=[5, 5, 3, 3],
        #initializer=tf.constant_initializer(Wcnn))
        #conv = tf.nn.conv2d(self.noise, Wcnn, [1, 1, 1, 1], padding='SAME',name='srm')
        #conv = tf.nn.conv2d(self.noise, kernel, [1, 1, 1, 1], padding='SAME',name='srm')
        #srm_conv = tf.nn.tanh(conv, name='tanh')
        with tf.variable_scope(self._resnet_scope, self._resnet_scope):
            net = resnet_utils.conv2d_same(self._image,
                                           64,
                                           7,
                                           stride=2,
                                           scope='conv1')
            net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
            net = slim.max_pool2d(net, [3, 3],
                                  stride=2,
                                  padding='VALID',
                                  scope='pool1')

        return net
Example #24
0
    def build_base(self):
        with tf.variable_scope(self._resnet_scope, self._resnet_scope):

            net = resnet_utils.conv2d_same(self._image,
                                           64,
                                           7,
                                           stride=2,
                                           scope='conv1')
            self._predictions[self._resnet_scope + '/conv1'] = net

            #       end_points_collection = self._resnet_scope + '_end_points'
            utils.collect_named_outputs(self._end_points_collection,
                                        self._resnet_scope + '/conv1', net)

            net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
            net = slim.max_pool2d(net, [3, 3],
                                  stride=2,
                                  padding='VALID',
                                  scope='pool1')

            return net
    def testConv2DSameOdd(self):
        n, n2 = 5, 3

        # Input image.
        x = create_test_input(1, n, n, 1)

        # Convolution kernel.
        w = create_test_input(1, 3, 3, 1)
        w = array_ops.reshape(w, [3, 3, 1, 1])

        variable_scope.get_variable('Conv/weights', initializer=w)
        variable_scope.get_variable('Conv/biases',
                                    initializer=array_ops.zeros([1]))
        variable_scope.get_variable_scope().reuse_variables()

        y1 = layers.conv2d(x, 1, [3, 3], stride=1, scope='Conv')
        y1_expected = math_ops.to_float([[14, 28, 43, 58, 34],
                                         [28, 48, 66, 84, 46],
                                         [43, 66, 84, 102, 55],
                                         [58, 84, 102, 120, 64],
                                         [34, 46, 55, 64, 30]])
        y1_expected = array_ops.reshape(y1_expected, [1, n, n, 1])

        y2 = resnet_utils.subsample(y1, 2)
        y2_expected = math_ops.to_float([[14, 43, 34], [43, 84, 55],
                                         [34, 55, 30]])
        y2_expected = array_ops.reshape(y2_expected, [1, n2, n2, 1])

        y3 = resnet_utils.conv2d_same(x, 1, 3, stride=2, scope='Conv')
        y3_expected = y2_expected

        y4 = layers.conv2d(x, 1, [3, 3], stride=2, scope='Conv')
        y4_expected = y2_expected

        with self.cached_session() as sess:
            sess.run(variables.global_variables_initializer())
            self.assertAllClose(y1.eval(), y1_expected.eval())
            self.assertAllClose(y2.eval(), y2_expected.eval())
            self.assertAllClose(y3.eval(), y3_expected.eval())
            self.assertAllClose(y4.eval(), y4_expected.eval())
Example #26
0
def resnet_v2_50(inputs,
                 num_classes=None,
                 is_training=True,
                 global_pool=False,
                 output_stride=None,
                 reuse=None,
                 scope='resnet_v2_50'):
    """ResNet-50 model of [1]. See resnet_v2() for arg and return description."""
    resnet_v2_block = resnet_v2.resnet_v2_block
    blocks = [
        resnet_v2_block('block1', base_depth=64, num_units=3, stride=2),
        resnet_v2_block('block2', base_depth=128, num_units=4, stride=2),
        resnet_v2_block('block3', base_depth=256, num_units=6, stride=2),
        resnet_v2_block('block4', base_depth=512, num_units=3, stride=1),
    ]

    # custom root block, because original root block will use maxpooling with valid padding.
    with tf.variable_scope(scope) as sc:
        with slim.arg_scope([slim.conv2d],
                            activation_fn=None,
                            normalizer_fn=None):
            net = resnet_utils.conv2d_same(inputs,
                                           64,
                                           7,
                                           stride=2,
                                           scope='conv1')  # stride 2
        net = slim.max_pool2d(net, [3, 3],
                              stride=2,
                              scope='pool1',
                              padding='SAME')  # stride 2
    return resnet_v2.resnet_v2(net,
                               blocks,
                               num_classes,
                               is_training=is_training,
                               global_pool=global_pool,
                               output_stride=output_stride,
                               include_root_block=False,
                               reuse=reuse,
                               scope=scope)
Example #27
0
def resnet50_reduced(inputs,
                     is_training=True,
                     output_stride=None,
                     include_root_block=True,
                     reuse=None,
                     scope=None):

    # These are the blocks for resnet 50
    blocks = [
        resnet_v1_block('block1', base_depth=64, num_units=3, stride=2),
        resnet_v1_block('block2', base_depth=128, num_units=4, stride=2),
        resnet_v1_block('block3', base_depth=256, num_units=6, stride=2),
        #        resnet_v1_block('block4', base_depth=512, num_units=3, stride=1),
    ]

    # Initialize Model
    with tf.variable_scope(scope, 'resnet_v1_50', [inputs], reuse=reuse):
        with slim.arg_scope(
            [slim.conv2d, bottleneck, resnet_utils.stack_blocks_dense]):
            with slim.arg_scope([slim.batch_norm],
                                is_training=is_training) as scope:
                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
                    net = resnet_utils.conv2d_same(net,
                                                   64,
                                                   7,
                                                   stride=2,
                                                   scope='conv1')
                    net = slim.max_pool2d(net, [3, 3], stride=2, scope='pool1')
                net = resnet_utils.stack_blocks_dense(net, blocks,
                                                      output_stride)
    return net
Example #28
0
def resnet50_reduced(inputs, is_training=True, output_stride=None, include_root_block=True, reuse=None, scope=None):

    # These are the blocks for resnet 50
    blocks = [
        resnet_v1_block('block1', base_depth=64, num_units=3, stride=2),
        resnet_v1_block('block2', base_depth=128, num_units=4, stride=2),
        resnet_v1_block('block3', base_depth=256, num_units=6, stride=2),
#        resnet_v1_block('block4', base_depth=512, num_units=3, stride=1),
        ]

    # Initialize Model
    with tf.variable_scope(scope, 'resnet_v1_50', [inputs], reuse=reuse):
        with slim.arg_scope([slim.conv2d, bottleneck, resnet_utils.stack_blocks_dense]):
            with slim.arg_scope([slim.batch_norm], is_training=is_training) as scope:
                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
                    net = resnet_utils.conv2d_same(net, 64, 7, stride=2, scope='conv1')
                    net = slim.max_pool2d(net, [3, 3], stride=2, scope='pool1')
                net = resnet_utils.stack_blocks_dense(net, blocks, output_stride)
    return net
  def testConv2DSameEven(self):
    n, n2 = 4, 2

    # Input image.
    x = create_test_input(1, n, n, 1)

    # Convolution kernel.
    w = create_test_input(1, 3, 3, 1)
    w = array_ops.reshape(w, [3, 3, 1, 1])

    variable_scope.get_variable('Conv/weights', initializer=w)
    variable_scope.get_variable('Conv/biases', initializer=array_ops.zeros([1]))
    variable_scope.get_variable_scope().reuse_variables()

    y1 = layers.conv2d(x, 1, [3, 3], stride=1, scope='Conv')
    y1_expected = math_ops.to_float([[14, 28, 43, 26], [28, 48, 66, 37],
                                     [43, 66, 84, 46], [26, 37, 46, 22]])
    y1_expected = array_ops.reshape(y1_expected, [1, n, n, 1])

    y2 = resnet_utils.subsample(y1, 2)
    y2_expected = math_ops.to_float([[14, 43], [43, 84]])
    y2_expected = array_ops.reshape(y2_expected, [1, n2, n2, 1])

    y3 = resnet_utils.conv2d_same(x, 1, 3, stride=2, scope='Conv')
    y3_expected = y2_expected

    y4 = layers.conv2d(x, 1, [3, 3], stride=2, scope='Conv')
    y4_expected = math_ops.to_float([[48, 37], [37, 22]])
    y4_expected = array_ops.reshape(y4_expected, [1, n2, n2, 1])

    with self.test_session() as sess:
      sess.run(variables.global_variables_initializer())
      self.assertAllClose(y1.eval(), y1_expected.eval())
      self.assertAllClose(y2.eval(), y2_expected.eval())
      self.assertAllClose(y3.eval(), y3_expected.eval())
      self.assertAllClose(y4.eval(), y4_expected.eval())
Example #30
0
  def build_base(self):
    with tf.variable_scope(self._resnet_scope, self._resnet_scope):
#       with arg_scope(
#         [slim.conv2d],
#         weights_regularizer=None,
#         weights_initializer=None,
#         trainable=False,
# #         activation_fn=nn_ops.relu,
#         activation_fn=None,
#         normalizer_fn=None,
#         normalizer_params=None,
#         biases_initializer=None): #make first layer clean, no BN no biases

      net = resnet_utils.conv2d_same(self._image, 64, 7, stride=2, scope='conv1')
      self._predictions[self._resnet_scope+'/conv1'] = net

#       end_points_collection = self._resnet_scope + '_end_points'
      utils.collect_named_outputs(self._end_points_collection, self._resnet_scope+'/conv1', 
                                  net)
      
      net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
      net = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='pool1')

      return net
Example #31
0
def resnet_v2(inputs,
              blocks,
              num_classes=None,
              is_training=None,
              global_pool=True,
              output_stride=None,
              include_root_block=True,
              reuse=None,
              scope=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. If None, the value inherited from
      the resnet_arg_scope is used. Specifying value None is deprecated.
    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.
    scope: 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.
  """
  with variable_scope.variable_scope(
      scope, 'resnet_v2', [inputs], reuse=reuse) as sc:
    end_points_collection = sc.original_name_scope + '_end_points'
    with arg_scope(
        [layers_lib.conv2d, bottleneck, resnet_utils.stack_blocks_dense],
        outputs_collections=end_points_collection):
      if is_training is not None:
        bn_scope = arg_scope([layers.batch_norm], is_training=is_training)
      else:
        bn_scope = arg_scope([])
      with bn_scope:
        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].
          with arg_scope(
              [layers_lib.conv2d], activation_fn=None, normalizer_fn=None):
            net = resnet_utils.conv2d_same(net, 64, 7, stride=2, scope='conv1')
          net = layers.max_pool2d(net, [3, 3], stride=2, scope='pool1')
        net = resnet_utils.stack_blocks_dense(net, blocks, output_stride)
        # 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 = layers.batch_norm(
            net, activation_fn=nn_ops.relu, scope='postnorm')
        if global_pool:
          # Global average pooling.
          net = math_ops.reduce_mean(net, [1, 2], name='pool5', keep_dims=True)
        if num_classes is not None:
          net = layers_lib.conv2d(
              net,
              num_classes, [1, 1],
              activation_fn=None,
              normalizer_fn=None,
              scope='logits')
        # Convert end_points_collection into a dictionary of end_points.
        end_points = utils.convert_collection_to_dict(end_points_collection)
        if num_classes is not None:
          end_points['predictions'] = layers.softmax(net, scope='predictions')
        return net, end_points
Example #32
0
def resnet_v2(inputs,
              blocks,
              num_classes=None,
              is_training=True,
              global_pool=True,
              output_stride=None,
              include_root_block=True,
              reuse=None,
              scope=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 batch_norm layers are in training mode.
    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.
    scope: 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.
  """
    with variable_scope.variable_scope(scope,
                                       'resnet_v2', [inputs],
                                       reuse=reuse) as sc:
        end_points_collection = sc.original_name_scope + '_end_points'
        with arg_scope(
            [layers_lib.conv2d, bottleneck, resnet_utils.stack_blocks_dense],
                outputs_collections=end_points_collection):
            with arg_scope([layers.batch_norm], is_training=is_training):
                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].
                    with arg_scope([layers_lib.conv2d],
                                   activation_fn=None,
                                   normalizer_fn=None):
                        net = resnet_utils.conv2d_same(net,
                                                       64,
                                                       7,
                                                       stride=2,
                                                       scope='conv1')
                    net = layers.max_pool2d(net, [3, 3],
                                            stride=2,
                                            scope='pool1',
                                            padding="SAME")
                net = resnet_utils.stack_blocks_dense(net, blocks,
                                                      output_stride)
                # 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 = layers.batch_norm(net,
                                        activation_fn=nn_ops.relu,
                                        scope='postnorm')
                if global_pool:
                    # Global average pooling.
                    import tensorflow as tf
                    net = tf.reduce_mean(net, [1, 2],
                                         name='pool5',
                                         keep_dims=True)
                if num_classes is not None:
                    net = layers_lib.conv2d(net,
                                            num_classes, [1, 1],
                                            activation_fn=None,
                                            normalizer_fn=None,
                                            scope='logits')
                # Convert end_points_collection into a dictionary of end_points.
                end_points = utils.convert_collection_to_dict(
                    end_points_collection)
                if num_classes is not None:
                    end_points['predictions'] = layers.softmax(
                        net, scope='predictions')
                return net, end_points
def densenet(inputs,
             num_classes=None,
             reduction=None,
             growth_rate=None,
             num_filters=None,
             convs_each_num_layers=None,
             dropout_rate=None,
             data_format='NHWC',
             is_training=True,
             include_root_block=True,
             reuse=None,
             base_net=True,
             global_pool=True,
             scope=None):
    assert reduction is not None
    assert growth_rate is not None
    assert num_filters is not None
    assert convs_each_num_layers is not None

    compression = 1.0 - reduction
    num_dense_blocks = len(convs_each_num_layers)

    if data_format == 'NCHW':
        inputs = tf.transpose(inputs, [0, 3, 1, 2])

    with tf.variable_scope(scope,
                           'densenetxxx', [inputs, num_classes],
                           reuse=reuse) as sc:
        end_points_collection = sc.name + '_end_points'
        with slim.arg_scope([slim.batch_norm, slim.dropout],
                         is_training=is_training), \
             slim.arg_scope([slim.conv2d, _conv, _conv_block,
                         _dense_block, _transition_block],
                         outputs_collections=end_points_collection), \
             slim.arg_scope([_conv], dropout_rate=dropout_rate):
            net = inputs

            if include_root_block:
                # initial convolution
                #                 net = slim.conv2d(net, num_filters, 7, stride=2, scope='conv1')
                #                 net = slim.batch_norm(net)
                #                 net = tf.nn.relu(net)
                #                 net = slim.max_pool2d(net, 3, stride=2, padding='SAME')
                net = resnet_utils.conv2d_same(net,
                                               64,
                                               7,
                                               stride=2,
                                               scope='conv1')
                net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]])
                net = slim.max_pool2d(net, [3, 3],
                                      stride=2,
                                      padding='VALID',
                                      scope='pool1')

            if base_net:
                # blocks
                for i in range(num_dense_blocks - 1):
                    # dense blocks
                    net, num_filters = _dense_block(net,
                                                    convs_each_num_layers[i],
                                                    num_filters,
                                                    growth_rate,
                                                    scope='dense_block' +
                                                    str(i + 1))

                    # Add transition_block
                    if i == num_dense_blocks - 2:
                        last_one = True
                    else:
                        last_one = False
                    net, num_filters = _transition_block(
                        net,
                        num_filters,
                        compression=compression,
                        last_one=last_one,
                        scope='transition_block' + str(i + 1))

                net, num_filters = _dense_block(net,
                                                convs_each_num_layers[-1],
                                                num_filters,
                                                growth_rate,
                                                scope='dense_block' +
                                                str(num_dense_blocks))
            else:
                for i in range(num_dense_blocks - 1):
                    # dense blocks
                    net, num_filters = _dense_block(net,
                                                    convs_each_num_layers[i],
                                                    num_filters, growth_rate)

                    # Add transition_block
                    net, num_filters = _transition_block(
                        net, num_filters, compression=compression)

                net, num_filters = _dense_block(net, convs_each_num_layers[-1],
                                                num_filters, growth_rate)

            # final blocks
            if global_pool:
                with tf.variable_scope('final_block', [inputs]):
                    net = slim.batch_norm(net)
                    net = tf.nn.relu(net)
                    net = _global_avg_pool2d(net, scope='global_avg_pool')

            if num_classes is not None:
                net = slim.conv2d(net,
                                  num_classes,
                                  1,
                                  biases_initializer=tf.zeros_initializer(),
                                  scope='logits')

            end_points = slim.utils.convert_collection_to_dict(
                end_points_collection)

            if num_classes is not None:
                end_points['predictions'] = slim.softmax(net,
                                                         scope='predictions')

            return net, end_points
Example #34
0
def bottleneck(inputs,
               depth,
               depth_bottleneck,
               stride,
               rate=1,
               outputs_collections=None,
               scope=None):
    """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.
      scope: Optional variable_scope.

    Returns:
      The ResNet unit's output.
    """
    with variable_scope.variable_scope(scope, 'bottleneck_v2', [inputs]) as sc:
        depth_in = utils.last_dimension(inputs.get_shape(), min_rank=4)
        preact = layers.batch_norm(inputs,
                                   activation_fn=nn_ops.relu,
                                   scope='preact')
        if depth == depth_in:
            shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')
        else:
            shortcut = layers_lib.conv2d(preact,
                                         depth, [1, 1],
                                         stride=stride,
                                         normalizer_fn=None,
                                         activation_fn=None,
                                         scope='shortcut')

        residual = layers_lib.conv2d(preact,
                                     depth_bottleneck, [1, 1],
                                     stride=1,
                                     scope='conv1')
        residual = resnet_utils.conv2d_same(residual,
                                            depth_bottleneck,
                                            3,
                                            stride,
                                            rate=rate,
                                            scope='conv2')
        residual = layers_lib.conv2d(residual,
                                     depth, [1, 1],
                                     stride=1,
                                     normalizer_fn=None,
                                     activation_fn=None,
                                     scope='conv3')

        random_range = 0.12  #if FLAGS.optimal else FLAGS.random_range
        weight = tf.random_uniform((depth, ),
                                   minval=1 - random_range,
                                   maxval=1 + random_range)
        # weight = tf.random_uniform((depth,), minval=5 - random_range, maxval=5 + random_range)
        output = weight * shortcut + residual
        # output = weight * shortcut + 0.5*residual

        return utils.collect_named_outputs(outputs_collections, sc.name,
                                           output)
Example #35
0
  def build_network(self, sess, is_training=True):
    # select initializers
    if cfg.TRAIN.TRUNCATED:
      initializer = tf.truncated_normal_initializer(mean=0.0, stddev=0.01)
      initializer_bbox = tf.truncated_normal_initializer(mean=0.0, stddev=0.001)
    else:
      #initializer = tf.random_normal_initializer(mean=0.0, stddev=0.01)
      initializer = tf.contrib.layers.xavier_initializer()
      initializer_bbox = tf.random_normal_initializer(mean=0.0, stddev=0.001)
    bottleneck = resnet_v1.bottleneck
    # choose different blocks for different number of layers
    if self._num_layers == 50:
      blocks = [
        resnet_utils.Block('block1', bottleneck,
                           [(256, 64, 1)] * 2 + [(256, 64, 2)]),
        resnet_utils.Block('block2', bottleneck,
                           [(512, 128, 1)] * 3 + [(512, 128, 2)]),
        # Use stride-1 for the last conv4 layer
        resnet_utils.Block('block3', bottleneck,
                           [(1024, 256, 1)] * 5 + [(1024, 256, 1)]),
        resnet_utils.Block('block4', bottleneck, [(2048, 512, 1)] * 3)
      ]
    elif self._num_layers == 101:
      blocks = [
        resnet_utils.Block('block1', bottleneck,
                           [(256, 64, 1)] * 2 + [(256, 64, 2)]),
        resnet_utils.Block('block2', bottleneck,
                           [(512, 128, 1)] * 3 + [(512, 128, 2)]),
        # Use stride-1 for the last conv4 layer
        resnet_utils.Block('block3', bottleneck,
                           [(1024, 256, 1)] * 22 + [(1024, 256, 1)]),
        resnet_utils.Block('block4', bottleneck, [(2048, 512, 1)] * 3)
      ]
    elif self._num_layers == 152:
      blocks = [
        resnet_utils.Block('block1', bottleneck,
                           [(256, 64, 1)] * 2 + [(256, 64, 2)]),
        resnet_utils.Block('block2', bottleneck,
                           [(512, 128, 1)] * 7 + [(512, 128, 2)]),
        # Use stride-1 for the last conv4 layer
        resnet_utils.Block('block3', bottleneck,
                           [(1024, 256, 1)] * 35 + [(1024, 256, 1)]),
        resnet_utils.Block('block4', bottleneck, [(2048, 512, 1)] * 3)
      ]
    else:
      # other numbers are not supported
      raise NotImplementedError

    assert (0 <= cfg.RESNET.FIXED_BLOCKS < 4)
    if cfg.RESNET.FIXED_BLOCKS == 3:
      with slim.arg_scope(resnet_arg_scope(is_training=False)):
        net = self.build_base()
        net_conv4, _ = resnet_v1.resnet_v1(net,
                                           blocks[0:cfg.RESNET.FIXED_BLOCKS],
                                           global_pool=False,
                                           include_root_block=False,
                                           scope=self._resnet_scope)
    elif cfg.RESNET.FIXED_BLOCKS > 0:
      with slim.arg_scope(resnet_arg_scope(is_training=False)):
        net = self.build_base()
        net, _ = resnet_v1.resnet_v1(net,
                                     blocks[0:cfg.RESNET.FIXED_BLOCKS],
                                     global_pool=False,
                                     include_root_block=False,
                                     scope=self._resnet_scope)

      with slim.arg_scope(resnet_arg_scope(is_training=is_training)):
        net_conv4, _ = resnet_v1.resnet_v1(net,
                                           blocks[cfg.RESNET.FIXED_BLOCKS:-1],
                                           global_pool=False,
                                           include_root_block=False,
                                           scope=self._resnet_scope)
    else:  # cfg.RESNET.FIXED_BLOCKS == 0
      with slim.arg_scope(resnet_arg_scope(is_training=is_training)):
        net = self.build_base()
        net_conv4, _ = resnet_v1.resnet_v1(net,
                                           blocks[0:-1],
                                           global_pool=False,
                                           include_root_block=False,
                                           scope=self._resnet_scope)
    self._act_summaries.append(net_conv4)
    self._layers['head'] = net_conv4
    c=np.zeros((3,5,5))
    c[0]=[[-1,2,-2,2,-1],[2,-6,8,-6,2],[-2,8,-12,8,-2],[2,-6,8,-6,2],[-1,2,-2,2,-1]]
    c[0]=c[0]/12

    c[1][1][1]=-1
    c[1][1][2]=2
    c[1][1][3]=-1
    c[1][2][1]=2
    c[1][2][2]=-4
    c[1][2][3]=2
    c[1][3][1]=-1
    c[1][3][2]=2
    c[1][3][3]=-1
    c[1]=c[1]/4

    c[2][2][1]=1
    c[2][2][2]=-2
    c[2][2][3]=1
    c[2]=c[2]/2

    Wcnn=np.zeros((5,5,3,3))
    for i in range(3):
      #k=i%10+1
      #Wcnn[i]=[c[3*k-3],c[3*k-2],c[3*k-1]]
      Wcnn[:,:,0,i]=c[i]
      Wcnn[:,:,1,i]=c[i]
      Wcnn[:,:,2,i]=c[i]
    if True:
      with tf.variable_scope('noise'):
        #kernel = tf.get_variable('weights',
                              #shape=[5, 5, 3, 3],
                              #initializer=tf.constant_initializer(c))
        conv = tf.nn.conv2d(self.noise, Wcnn, [1, 1, 1, 1], padding='SAME',name='srm')
      self._layers['noise']=conv
      with slim.arg_scope(resnet_arg_scope(is_training=is_training)):
        #srm_conv = tf.nn.tanh(conv, name='tanh')
        noise_net = resnet_utils.conv2d_same(conv, 64, 7, stride=2, scope='conv1')
        noise_net = tf.pad(noise_net, [[0, 0], [1, 1], [1, 1], [0, 0]])
        noise_net = slim.max_pool2d(noise_net, [3, 3], stride=2, padding='VALID', scope='pool1')
        #net_sum=tf.concat(3,[net_conv4,noise_net])
        noise_conv4, _ = resnet_v1.resnet_v1(noise_net,
                                           blocks[0:-1],
                                           global_pool=False,
                                           include_root_block=False,
                                           scope='noise')
    with tf.variable_scope(self._resnet_scope, self._resnet_scope):
      # build the anchors for the image
      self._anchor_component()

      # rpn
      rpn = slim.conv2d(net_conv4, 512, [3, 3], trainable=is_training, weights_initializer=initializer,
                        scope="rpn_conv/3x3")
      self._act_summaries.append(rpn)
      rpn_cls_score = slim.conv2d(rpn, self._num_anchors * 2, [1, 1], trainable=is_training,
                                  weights_initializer=initializer,
                                  padding='VALID', activation_fn=None, scope='rpn_cls_score')
      # change it so that the score has 2 as its channel size
      rpn_cls_score_reshape = self._reshape_layer(rpn_cls_score, 2, 'rpn_cls_score_reshape')
      rpn_cls_prob_reshape = self._softmax_layer(rpn_cls_score_reshape, "rpn_cls_prob_reshape")
      rpn_cls_prob = self._reshape_layer(rpn_cls_prob_reshape, self._num_anchors * 2, "rpn_cls_prob")
      rpn_bbox_pred = slim.conv2d(rpn, self._num_anchors * 4, [1, 1], trainable=is_training,
                                  weights_initializer=initializer,
                                  padding='VALID', activation_fn=None, scope='rpn_bbox_pred')
      if is_training:
        rois, roi_scores = self._proposal_layer(rpn_cls_prob, rpn_bbox_pred, "rois")
        rpn_labels = self._anchor_target_layer(rpn_cls_score, "anchor")
        # Try to have a determinestic order for the computing graph, for reproducibility
        with tf.control_dependencies([rpn_labels]):
          rois, _ = self._proposal_target_layer(rois, roi_scores, "rpn_rois")
      else:
        if cfg.TEST.MODE == 'nms':
          rois, _ = self._proposal_layer(rpn_cls_prob, rpn_bbox_pred, "rois")
        elif cfg.TEST.MODE == 'top':
          rois, _ = self._proposal_top_layer(rpn_cls_prob, rpn_bbox_pred, "rois")
        else:
          raise NotImplementedError
      # rcnn
      if cfg.POOLING_MODE == 'crop':
        pool5 = self._crop_pool_layer(net_conv4, rois, "pool5")
        self._layers['pool5']=pool5
        #pool5 = self._crop_pool_layer(net_sum, rois, "pool5")
      else:
        raise NotImplementedError
    if True:
      noise_pool5 = self._crop_pool_layer(noise_conv4, rois, "noise_pool5")
      with slim.arg_scope(resnet_arg_scope(is_training=is_training)):
        noise_fc7, _ = resnet_v1.resnet_v1(noise_pool5,
                                   blocks[-1:],
                                   global_pool=False,
                                   include_root_block=False,
                                   scope='noise')
    with slim.arg_scope(resnet_arg_scope(is_training=is_training)):
      fc7, _ = resnet_v1.resnet_v1(pool5,
                                   blocks[-1:],
                                   global_pool=False,
                                   include_root_block=False,
                                   scope=self._resnet_scope)
    self._layers['fc7']=fc7
    with tf.variable_scope('noise_pred'):

      bilinear_pool=compact_bilinear_pooling_layer(fc7,noise_fc7,2048*8,compute_size=16,sequential=False)
      fc7=tf.Print(fc7,[tf.shape(fc7)],message='Value of %s' % 'fc', summarize=4, first_n=1)
      bilinear_pool=tf.reshape(bilinear_pool, [-1,2048*8])
      bilinear_pool=tf.Print(bilinear_pool,[tf.shape(bilinear_pool)],message='Value of %s' % 'Blinear', summarize=4, first_n=1)
      bilinear_pool=tf.multiply(tf.sign(bilinear_pool),tf.sqrt(tf.abs(bilinear_pool)+1e-12))
      bilinear_pool=tf.nn.l2_normalize(bilinear_pool,dim=1)
      noise_cls_score = slim.fully_connected(bilinear_pool, self._num_classes, weights_initializer=tf.contrib.layers.xavier_initializer(),
                                       trainable=is_training, activation_fn=None, scope='cls_score')
      cls_prob = self._softmax_layer(noise_cls_score, "cls_prob")
      fc7 = tf.reduce_mean(fc7, axis=[1, 2])




      bbox_pred = slim.fully_connected(fc7, self._num_classes * 4, weights_initializer=initializer_bbox,
                                     trainable=is_training,
                                     activation_fn=None, scope='bbox_pred')

    self._predictions["rpn_cls_score"] = rpn_cls_score
    self._predictions["rpn_cls_score_reshape"] = rpn_cls_score_reshape
    self._predictions["rpn_cls_prob"] = rpn_cls_prob
    self._predictions["rpn_bbox_pred"] = rpn_bbox_pred
    self._predictions["cls_score"] = noise_cls_score
    self._predictions["cls_prob"] = cls_prob
    self._predictions["bbox_pred"] = bbox_pred
    self._predictions["rois"] = rois

    self._score_summaries.update(self._predictions)

    return rois, cls_prob,bbox_pred
def mobilenet_v1_base(inputs,
                      conv_defs,
                      starting_layer=0,
                      min_depth=8,
                      depth_multiplier=1.0,
                      output_stride=None,
                      reuse=None,
                      scope=None):
    """Mobilenet v1.
  Constructs a Mobilenet v1 network from inputs to the given final endpoint.
  Args:
    inputs: a tensor of shape [batch_size, height, width, channels].
    starting_layer: specifies the current starting layer. For region proposal 
      network it is 0, for region classification it is 12 by default.
    min_depth: Minimum depth value (number of channels) for all convolution ops.
      Enforced when depth_multiplier < 1, and not an active constraint when
      depth_multiplier >= 1.
    depth_multiplier: Float multiplier for the depth (number of channels)
      for all convolution ops. The value must be greater than zero. Typical
      usage will be to set this value in (0, 1) to reduce the number of
      parameters or computation cost of the model.
    conv_defs: A list of ConvDef named tuples specifying the net architecture.
    output_stride: An integer that specifies the requested ratio of input to
      output spatial resolution. If not None, then we invoke atrous convolution
      if necessary to prevent the network from reducing the spatial resolution
      of the activation maps. 
    scope: Optional variable_scope.
  Returns:
    tensor_out: output tensor corresponding to the final_endpoint.
  Raises:
    ValueError: if depth_multiplier <= 0, or convolution type is not defined.
  """
    depth = lambda d: max(int(d * depth_multiplier), min_depth)
    end_points = {}

    # Used to find thinned depths for each layer.
    if depth_multiplier <= 0:
        raise ValueError('depth_multiplier is not greater than zero.')

    with tf.variable_scope(scope, 'MobilenetV1', [inputs], reuse=reuse):
        # The current_stride variable keeps track of the output stride of the
        # activations, i.e., the running product of convolution strides up to the
        # current network layer. This allows us to invoke atrous convolution
        # whenever applying the next convolution would result in the activations
        # having output stride larger than the target output_stride.
        current_stride = 1

        # The atrous convolution rate parameter.
        rate = 1

        net = inputs
        for i, conv_def in enumerate(conv_defs):
            end_point_base = 'Conv2d_%d' % (i + starting_layer)

            if output_stride is not None and current_stride == output_stride:
                # If we have reached the target output_stride, then we need to employ
                # atrous convolution with stride=1 and multiply the atrous rate by the
                # current unit's stride for use in subsequent layers.
                layer_stride = 1
                layer_rate = rate
                rate *= conv_def.stride
            else:
                layer_stride = conv_def.stride
                layer_rate = 1
                current_stride *= conv_def.stride

            if isinstance(conv_def, Conv):
                end_point = end_point_base
                net = resnet_utils.conv2d_same(net,
                                               depth(conv_def.depth),
                                               conv_def.kernel,
                                               stride=conv_def.stride,
                                               scope=end_point)

            elif isinstance(conv_def, DepthSepConv):
                end_point = end_point_base + '_depthwise'

                net = separable_conv2d_same(net,
                                            conv_def.kernel,
                                            stride=layer_stride,
                                            rate=layer_rate,
                                            scope=end_point)

                end_point = end_point_base + '_pointwise'

                net = slim.conv2d(net,
                                  depth(conv_def.depth), [1, 1],
                                  stride=1,
                                  scope=end_point)

            else:
                raise ValueError('Unknown convolution type %s for layer %d' %
                                 (conv_def.ltype, i))

        return net
def mobilenet_v1_base(inputs,
                      conv_defs,
                      starting_layer=0,
                      min_depth=8,
                      depth_multiplier=1.0,
                      output_stride=None,
                      reuse=None,
                      scope=None):
  """Mobilenet v1.
  Constructs a Mobilenet v1 network from inputs to the given final endpoint.
  Args:
    inputs: a tensor of shape [batch_size, height, width, channels].
    starting_layer: specifies the current starting layer. For region proposal 
      network it is 0, for region classification it is 12 by default.
    min_depth: Minimum depth value (number of channels) for all convolution ops.
      Enforced when depth_multiplier < 1, and not an active constraint when
      depth_multiplier >= 1.
    depth_multiplier: Float multiplier for the depth (number of channels)
      for all convolution ops. The value must be greater than zero. Typical
      usage will be to set this value in (0, 1) to reduce the number of
      parameters or computation cost of the model.
    conv_defs: A list of ConvDef named tuples specifying the net architecture.
    output_stride: An integer that specifies the requested ratio of input to
      output spatial resolution. If not None, then we invoke atrous convolution
      if necessary to prevent the network from reducing the spatial resolution
      of the activation maps. 
    scope: Optional variable_scope.
  Returns:
    tensor_out: output tensor corresponding to the final_endpoint.
  Raises:
    ValueError: if depth_multiplier <= 0, or convolution type is not defined.
  """
  depth = lambda d: max(int(d * depth_multiplier), min_depth)
  end_points = {}

  # Used to find thinned depths for each layer.
  if depth_multiplier <= 0:
    raise ValueError('depth_multiplier is not greater than zero.')

  with tf.variable_scope(scope, 'MobilenetV1', [inputs], reuse=reuse):
    # The current_stride variable keeps track of the output stride of the
    # activations, i.e., the running product of convolution strides up to the
    # current network layer. This allows us to invoke atrous convolution
    # whenever applying the next convolution would result in the activations
    # having output stride larger than the target output_stride.
    current_stride = 1

    # The atrous convolution rate parameter.
    rate = 1

    net = inputs
    for i, conv_def in enumerate(conv_defs):
      end_point_base = 'Conv2d_%d' % (i + starting_layer)

      if output_stride is not None and current_stride == output_stride:
        # If we have reached the target output_stride, then we need to employ
        # atrous convolution with stride=1 and multiply the atrous rate by the
        # current unit's stride for use in subsequent layers.
        layer_stride = 1
        layer_rate = rate
        rate *= conv_def.stride
      else:
        layer_stride = conv_def.stride
        layer_rate = 1
        current_stride *= conv_def.stride

      if isinstance(conv_def, Conv):
        end_point = end_point_base
        net = resnet_utils.conv2d_same(net, depth(conv_def.depth), conv_def.kernel,
                          stride=conv_def.stride,
                          scope=end_point)

      elif isinstance(conv_def, DepthSepConv):
        end_point = end_point_base + '_depthwise'
        
        net = separable_conv2d_same(net, conv_def.kernel,
                                    stride=layer_stride,
                                    rate=layer_rate,
                                    scope=end_point)

        end_point = end_point_base + '_pointwise'

        net = slim.conv2d(net, depth(conv_def.depth), [1, 1],
                          stride=1,
                          scope=end_point)

      else:
        raise ValueError('Unknown convolution type %s for layer %d'
                         % (conv_def.ltype, i))

    return net
Example #38
0
    def build_network(self, sess, is_training=True):
        # select initializers
        if cfg.TRAIN.TRUNCATED:
            initializer = tf.truncated_normal_initializer(mean=0.0,
                                                          stddev=0.01)
            initializer_bbox = tf.truncated_normal_initializer(mean=0.0,
                                                               stddev=0.001)
        else:
            initializer = tf.random_normal_initializer(mean=0.0, stddev=0.01)
            initializer_bbox = tf.random_normal_initializer(mean=0.0,
                                                            stddev=0.001)
        bottleneck = resnet_v1.bottleneck
        # choose different blocks for different number of layers
        if self._num_layers == 50:
            blocks = [
                resnet_utils.Block('block1', bottleneck,
                                   [(256, 64, 1)] * 2 + [(256, 64, 2)]),
                resnet_utils.Block('block2', bottleneck,
                                   [(512, 128, 1)] * 3 + [(512, 128, 2)]),
                # Use stride-1 for the last conv4 layer
                resnet_utils.Block('block3', bottleneck,
                                   [(1024, 256, 1)] * 5 + [(1024, 256, 1)]),
                resnet_utils.Block('block4', bottleneck, [(2048, 512, 1)] * 3)
            ]
        elif self._num_layers == 101:
            blocks = [
                resnet_utils.Block('block1', bottleneck,
                                   [(256, 64, 1)] * 2 + [(256, 64, 2)]),
                resnet_utils.Block('block2', bottleneck,
                                   [(512, 128, 1)] * 3 + [(512, 128, 2)]),
                # Use stride-1 for the last conv4 layer
                resnet_utils.Block('block3', bottleneck,
                                   [(1024, 256, 1)] * 22 + [(1024, 256, 1)]),
                resnet_utils.Block('block4', bottleneck, [(2048, 512, 1)] * 3)
            ]
        elif self._num_layers == 152:
            blocks = [
                resnet_utils.Block('block1', bottleneck,
                                   [(256, 64, 1)] * 2 + [(256, 64, 2)]),
                resnet_utils.Block('block2', bottleneck,
                                   [(512, 128, 1)] * 7 + [(512, 128, 2)]),
                # Use stride-1 for the last conv4 layer
                resnet_utils.Block('block3', bottleneck,
                                   [(1024, 256, 1)] * 35 + [(1024, 256, 1)]),
                resnet_utils.Block('block4', bottleneck, [(2048, 512, 1)] * 3)
            ]
        else:
            # other numbers are not supported
            raise NotImplementedError

        assert (0 <= cfg.RESNET.FIXED_BLOCKS < 4)
        if cfg.RESNET.FIXED_BLOCKS == 3:
            with slim.arg_scope(resnet_arg_scope(is_training=False)):
                net = self.build_base()
                net_conv4, _ = resnet_v1.resnet_v1(
                    net,
                    blocks[0:cfg.RESNET.FIXED_BLOCKS],
                    global_pool=False,
                    include_root_block=False,
                    scope=self._resnet_scope)
        elif cfg.RESNET.FIXED_BLOCKS > 0:
            with slim.arg_scope(resnet_arg_scope(is_training=False)):
                net = self.build_base()
                net, _ = resnet_v1.resnet_v1(net,
                                             blocks[0:cfg.RESNET.FIXED_BLOCKS],
                                             global_pool=False,
                                             include_root_block=False,
                                             scope=self._resnet_scope)

            with slim.arg_scope(resnet_arg_scope(is_training=is_training)):
                net_conv4, _ = resnet_v1.resnet_v1(
                    net,
                    blocks[cfg.RESNET.FIXED_BLOCKS:-1],
                    global_pool=False,
                    include_root_block=False,
                    scope=self._resnet_scope)
        else:  # cfg.RESNET.FIXED_BLOCKS == 0
            with slim.arg_scope(resnet_arg_scope(is_training=is_training)):
                net = self.build_base()
                net_conv4, _ = resnet_v1.resnet_v1(net,
                                                   blocks[0:-1],
                                                   global_pool=False,
                                                   include_root_block=False,
                                                   scope=self._resnet_scope)
        self._act_summaries.append(net_conv4)
        self._layers['head'] = net_conv4

        if False:
            with tf.variable_scope('noise'):
                #kernel = tf.get_variable('weights',
                #shape=[5, 5, 3, 3],
                #initializer=tf.constant_initializer(c))
                conv = tf.nn.conv2d(self.noise,
                                    Wcnn, [1, 1, 1, 1],
                                    padding='SAME',
                                    name='srm')
            self._layers['noise'] = conv
            with slim.arg_scope(resnet_arg_scope(is_training=is_training)):
                #srm_conv = tf.nn.tanh(conv, name='tanh')
                noise_net = resnet_utils.conv2d_same(conv,
                                                     64,
                                                     7,
                                                     stride=2,
                                                     scope='conv1')
                noise_net = tf.pad(noise_net, [[0, 0], [1, 1], [1, 1], [0, 0]])
                noise_net = slim.max_pool2d(noise_net, [3, 3],
                                            stride=2,
                                            padding='VALID',
                                            scope='pool1')
                #net_sum=tf.concat(3,[net_conv4,noise_net])
                noise_conv4, _ = resnet_v1.resnet_v1(noise_net,
                                                     blocks[0:-1],
                                                     global_pool=False,
                                                     include_root_block=False,
                                                     scope='noise')
        with tf.variable_scope(self._resnet_scope, self._resnet_scope):
            # build the anchors for the image
            self._anchor_component()

            # rpn
            rpn = slim.conv2d(net_conv4,
                              512, [3, 3],
                              trainable=is_training,
                              weights_initializer=initializer,
                              scope="rpn_conv/3x3")
            self._act_summaries.append(rpn)
            rpn_cls_score = slim.conv2d(rpn,
                                        self._num_anchors * 2, [1, 1],
                                        trainable=is_training,
                                        weights_initializer=initializer,
                                        padding='VALID',
                                        activation_fn=None,
                                        scope='rpn_cls_score')
            # change it so that the score has 2 as its channel size
            rpn_cls_score_reshape = self._reshape_layer(
                rpn_cls_score, 2, 'rpn_cls_score_reshape')
            rpn_cls_prob_reshape = self._softmax_layer(rpn_cls_score_reshape,
                                                       "rpn_cls_prob_reshape")
            rpn_cls_prob = self._reshape_layer(rpn_cls_prob_reshape,
                                               self._num_anchors * 2,
                                               "rpn_cls_prob")
            rpn_bbox_pred = slim.conv2d(rpn,
                                        self._num_anchors * 4, [1, 1],
                                        trainable=is_training,
                                        weights_initializer=initializer,
                                        padding='VALID',
                                        activation_fn=None,
                                        scope='rpn_bbox_pred')
            if is_training:
                rois, roi_scores = self._proposal_layer(
                    rpn_cls_prob, rpn_bbox_pred, "rois")
                rpn_labels = self._anchor_target_layer(rpn_cls_score, "anchor")
                # Try to have a determinestic order for the computing graph, for reproducibility
                with tf.control_dependencies([rpn_labels]):
                    rois, _ = self._proposal_target_layer(
                        rois, roi_scores, "rpn_rois")
            else:
                if cfg.TEST.MODE == 'nms':
                    rois, _ = self._proposal_layer(rpn_cls_prob, rpn_bbox_pred,
                                                   "rois")
                elif cfg.TEST.MODE == 'top':
                    rois, _ = self._proposal_top_layer(rpn_cls_prob,
                                                       rpn_bbox_pred, "rois")
                else:
                    raise NotImplementedError
            # rcnn
            if cfg.POOLING_MODE == 'crop':
                pool5 = self._crop_pool_layer(net_conv4, rois, "pool5")
                #pool5 = self._crop_pool_layer(net_sum, rois, "pool5")
            else:
                raise NotImplementedError
        if False:
            noise_pool5 = self._crop_pool_layer(noise_conv4, rois,
                                                "noise_pool5")
            with slim.arg_scope(resnet_arg_scope(is_training=is_training)):
                noise_fc7, _ = resnet_v1.resnet_v1(noise_pool5,
                                                   blocks[-1:],
                                                   global_pool=False,
                                                   include_root_block=False,
                                                   scope='noise')
        with slim.arg_scope(resnet_arg_scope(is_training=is_training)):
            fc7, _ = resnet_v1.resnet_v1(pool5,
                                         blocks[-1:],
                                         global_pool=False,
                                         include_root_block=False,
                                         scope=self._resnet_scope)
        self._layers['fc7'] = fc7
        with tf.variable_scope(self._resnet_scope, self._resnet_scope):
            #pdb.set_trace()
            #noise_fc7 = tf.reduce_mean(noise_fc7, axis=[1, 2])
            #bilinear_pool=compact_bilinear_pooling_layer(fc7,noise_fc7,2048*4,compute_size=16,sequential=False)
            #bilinear_pool=tf.reshape(bilinear_pool, [-1,2048*4])
            fc7 = tf.reduce_mean(fc7, axis=[1, 2])
            cls_score = slim.fully_connected(fc7,
                                             self._num_classes,
                                             weights_initializer=initializer,
                                             trainable=is_training,
                                             activation_fn=None,
                                             scope='cls_score')
            #pdb.set_trace()
            #noise_cls_score = slim.fully_connected(bilinear_pool, self._num_classes, weights_initializer=initializer,
            #trainable=is_training, activation_fn=None, scope='noise_cls_score')
            cls_prob = self._softmax_layer(cls_score, "cls_prob")
            bbox_pred = slim.fully_connected(
                fc7,
                self._num_classes * 4,
                weights_initializer=initializer_bbox,
                trainable=is_training,
                activation_fn=None,
                scope='bbox_pred')
        #with tf.variable_scope(self._resnet_scope, self._resnet_scope):
        # Average pooling done by reduce_mean
        #fc7 = tf.reduce_mean(fc7, axis=[1, 2])
        #fc_con=tf.concat(1,[fc7,noise_fc])
        #cls_score = slim.fully_connected(fc7, self._num_classes, weights_initializer=initializer,
        #trainable=False, activation_fn=None, scope='cls_score')
        #cls_score1=cls_score+10*noise_cls_score
        #cls_prob = self._softmax_layer(noise_cls_score, "cls_prob")
        #bbox_pred = slim.fully_connected(fc7, self._num_classes * 4, weights_initializer=initializer_bbox,
        #trainable=False,
        #activation_fn=None, scope='bbox_pred')
        self._predictions["rpn_cls_score"] = rpn_cls_score
        self._predictions["rpn_cls_score_reshape"] = rpn_cls_score_reshape
        self._predictions["rpn_cls_prob"] = rpn_cls_prob
        self._predictions["rpn_bbox_pred"] = rpn_bbox_pred
        self._predictions["cls_score"] = cls_score
        self._predictions["cls_prob"] = cls_prob
        self._predictions["bbox_pred"] = bbox_pred
        self._predictions["rois"] = rois

        self._score_summaries.update(self._predictions)

        return rois, cls_prob, bbox_pred