def resnet50_part2(inputs, is_training, embedding_dim, scope='resnet_v2_50', reuse=False): with tf.variable_scope(scope, reuse=reuse): with arg_scope(resnet_arg_scope(is_training=is_training)): out = resnet_v2_block(inputs=inputs, base_depth=256, num_units=6, stride=2, scope='block3') out = resnet_v2_block(inputs=out, base_depth=512, num_units=3, stride=1, scope='block4') out = layers.batch_norm(out, activation_fn=nn_ops.relu, scope='postnorm') avg_out = tf.reduce_mean(out, axis=[1, 2], name='pool5') with tf.variable_scope('fc', reuse=reuse): with arg_scope(resnet_arg_scope(is_training=is_training)): fc_out = layers_lib.fully_connected(inputs=avg_out, num_outputs=embedding_dim, activation_fn=None) fc_out = layers.batch_norm(fc_out, activation_fn=None, scope='out_norm') return fc_out
def batch_norm_layer(self, signal, scope, activation_fn=None): return tf.cond( self.is_training, lambda: batch_norm(signal, is_training=True, param_initializers={ "beta": tf.constant_initializer(3.), "gamma": tf.constant_initializer(2.5) }, center=True, scale=True, activation_fn=activation_fn, decay=1.0, scope=scope), lambda: batch_norm(signal, is_training=False, param_initializers={ "beta": tf.constant_initializer(3.), "gamma": tf.constant_initializer(2.5) }, center=True, scale=True, activation_fn=activation_fn, decay=1.0, scope=scope, reuse=True))
def batch_norm_layer(self, signal, scope): ''' batch normalization layer before activation :param signal: input signal :param scope: name scope :return: normalized signal ''' # Note: is_training is tf.placeholder(tf.bool) type return tf.cond( self.is_training, lambda: batch_norm(signal, is_training=True, param_initializers={ "beta": tf.constant_initializer(3.), "gamma": tf.constant_initializer(2.5) }, center=True, scale=True, activation_fn=tf.nn.relu, decay=1., scope=scope), lambda: batch_norm(signal, is_training=False, param_initializers={ "beta": tf.constant_initializer(3.), "gamma": tf.constant_initializer(2.5) }, center=True, scale=True, activation_fn=tf.nn.relu, decay=1., scope=scope, reuse=True))
def add_BN_conv_layer(inputs, kernalWidth, inDepth, outDepth, is_training_ph, scope , layername="layer", activateFunc=tf.nn.relu, stride=[1, 1, 1, 1]): # inDepth = inputs.get_shape().as_list()[3] with tf.name_scope(layername): n = kernalWidth * kernalWidth * outDepth Weights = tf.Variable(tf.truncated_normal([kernalWidth, kernalWidth, inDepth, outDepth], stddev=np.sqrt(2.0/n))) biases = tf.Variable(tf.constant(0.1, tf.float32, [outDepth])) y1 = tf.nn.conv2d(inputs, Weights, stride, padding='SAME') + biases outputs = tf.cond(is_training_ph, lambda: batch_norm(y1,decay=0.94, is_training=True, center=False, scale=True, activation_fn=activateFunc, updates_collections=None, scope=scope), lambda: batch_norm(y1,decay=0.94, is_training=False, center=False, scale=True, activation_fn=activateFunc, updates_collections=None, scope=scope, reuse=True)) return outputs
def batch_norm(input, is_training=None, scope=None, reuse=False): # return tf.cond(tf.equal(is_training, tf.constant(1, dtype=tf.int8)), return tf.cond( is_training, lambda: layers.batch_norm(input, is_training=True, scope=scope, reuse=reuse, **batch_norm_params), lambda: layers.batch_norm(input, is_training=False, scope=scope, reuse=True, **batch_norm_params))
def split_batch_norm(inputs, Nb_list, *args, **kwargs): log.debug('You are splitting the batchnorm layers') if len(Nb_list) > 1: with tf.variable_scope('bn_split'): source_output = layers.batch_norm(inputs=inputs[:Nb_list[0]], *args, **kwargs) with tf.variable_scope('bn_split', reuse=True): target_output = layers.batch_norm(inputs=inputs[Nb_list[0]:], *args, **kwargs) # with tf.variable_scope("split_bn_target"): # # TODO initialize the layers of target with also parameters from the ResNET checkpoints # kwargs.update({'param_regularizers': {'beta': l2_regularizer(0.00017)}}) # target_output = layers.batch_norm(inputs=inputs[Nb_list[0]:], *args, **kwargs) return concat((source_output, target_output), axis=0) else: with tf.variable_scope("bn_split"): return layers.batch_norm(inputs=inputs, *args, **kwargs)
def _score_layer(self, bottom, name, num_classes,is_bn=True, train=True): with tf.variable_scope(name) as scope: # get number of input channels in_features = bottom.get_shape()[3].value shape = [1, 1, in_features, num_classes] # He initialization Sheme if name == "score_fr": num_input = in_features stddev = (2 / num_input)**0.5 elif name == "score_pool4": stddev = 0.001 elif name == "score_pool3": stddev = 0.0001 # Apply convolution w_decay = self.wd weights = self._variable_with_weight_decay(shape, stddev, w_decay, decoder=True) conv = tf.nn.conv2d(bottom, weights, [1, 1, 1, 1], padding='SAME') # Apply bias conv_biases = self._bias_variable([num_classes], constant=0.0) bias = tf.nn.bias_add(conv, conv_biases) # _activation_summary(bias) if (is_bn): # return utils.bn_layer(relu, is_training) return layers.batch_norm(bias, scope='afternorm', is_training=train) else: return bias
def _fc_layer(self, bottom, name, shape, load=False, num_classes=None, relu=True, debug=False, is_bn = True, train = True): with tf.variable_scope(name) as scope: if name == 'score_fr': name = 'fc8' filt = self.get_fc_weight_reshape(name, shape, load=load, num_classes=num_classes) else: filt = self.get_fc_weight_reshape(name, shape, load=load) conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME') conv_biases = self.get_bias(name, shape[3], load=load, num_classes=num_classes) bias = tf.nn.bias_add(conv, conv_biases) if relu: bias = tf.nn.relu(bias) # _activation_summary(bias) if debug: bias = tf.Print(bias, [tf.shape(bias)], message='Shape of %s' % name, summarize=4, first_n=1) if (is_bn): # return utils.bn_layer(relu, is_training) return layers.batch_norm(bias, scope='afternorm', is_training=train) else: return bias
def conv_block(inp, relu=False, leaky_relu=False, bn=False, output_channels=64, stride=1, is_training_cond=None, reuse=False): inp_shape = inp.get_shape() kernel_shape = (3, 3, inp_shape[-1], output_channels) strides = [1, stride, stride, 1] weights = tf.get_variable( 'weights', kernel_shape, initializer=tf.random_normal_initializer(stddev=0.02)) h = tf.nn.conv2d(inp, weights, strides, padding='SAME') if leaky_relu: h = relu_block(h, alpha=0.01) if bn: h = batch_norm(h, reuse=reuse, is_training=is_training_cond, scope=tf.get_variable_scope(), scale=True) if relu: h = tf.nn.relu(h) return h
def _LayerWithIdentity(self, input_tensor=None, scope='test', post_activation_bypass=False): """Add a basic conv, identity, batch norm with skip to the default graph.""" batch_size, height, width, depth = 5, 128, 128, 3 if input_tensor is None: input_tensor = array_ops.zeros((batch_size, height, width, depth)) weight_init = init_ops.truncated_normal_initializer with ops.name_scope(scope): output = layers.conv2d(input_tensor, depth, [5, 5], padding='SAME', weights_initializer=weight_init(0.09), activation_fn=None, normalizer_fn=None, biases_initializer=None) output = array_ops.identity(output, name='conv_out') output = layers.batch_norm(output, center=True, scale=True, decay=1.0 - 0.003, fused=True) output = array_ops.identity(output, name='bn_out') if post_activation_bypass: output += input_tensor return output
def model(images, filter_type, filter_trainable, weight_decay, batch_size, is_training, num_classes=2): with slim.arg_scope(resnet_v2.resnet_arg_scope(weight_decay=weight_decay)): inputs = get_residuals(images, filter_type, filter_trainable) _, end_points = resnet_small(inputs, num_classes=None, is_training=is_training, global_pool=False, output_stride=None, include_root_block=False) net = end_points['resnet_small/block4'] net = tf.nn.conv2d_transpose(net, tf.Variable(bilinear_upsample_weights(4,64,1024),dtype=tf.float32,name='bilinear_kernel0'), \ [batch_size, tf.shape(end_points['resnet_small/block2'])[1], tf.shape(end_points['resnet_small/block2'])[2], 64], strides=[1, 4, 4, 1], padding="SAME") end_points['upsample1'] = net net = tf.nn.conv2d_transpose(net, tf.Variable(bilinear_upsample_weights(4,4,64),dtype=tf.float32,name='bilinear_kernel1'), \ [batch_size, tf.shape(inputs)[1], tf.shape(inputs)[2], 4], strides=[1, 4, 4, 1], padding="SAME") end_points['upsample2'] = net net = layers.batch_norm(net, activation_fn=tf.nn.relu, is_training=is_training, scope='post_norm') logits = slim.conv2d(net, num_classes, [5, 5], activation_fn=None, normalizer_fn=None, scope='logits') preds = tf.cast(tf.argmax(logits, 3), tf.int32) preds_map = tf.nn.softmax(logits)[:, :, :, 1] return logits, preds, preds_map, net, end_points, inputs
def _LayerWithActivationProcessing(self, input_tensor=None, scope='test', post_activation_bypass=False): batch_size, height, width, depth = 5, 128, 128, 3 if input_tensor is None: input_tensor = array_ops.zeros((batch_size, height, width, depth)) weight_init = init_ops.truncated_normal_initializer with ops.name_scope(scope): output = layers.conv2d( input_tensor, depth, [5, 5], padding='SAME', weights_initializer=weight_init(0.09), activation_fn=None, normalizer_fn=None, biases_initializer=None) output = layers.batch_norm( output, center=True, scale=True, decay=1.0 - 0.003, fused=True) output = nn_ops.relu6(output) scaled_output1 = math_ops.mul(2.0, output) scaled_output2 = math_ops.mul(3.0, output) output = scaled_output1 + scaled_output2 return output
def _conv3d(input_data, k_d, k_h, k_w, c_o, s_d, s_h, s_w, name, relu=True, padding="SAME"): c_i = input_data.get_shape()[-1].value convolve = lambda i, k: tf.nn.conv3d( i, k, [1, s_d, s_h, s_w, 1], padding=padding) with tf.variable_scope(name) as scope: weights = tf.get_variable( name="weights", shape=[k_d, k_h, k_w, c_i, c_o], regularizer=tf.contrib.layers.l2_regularizer(scale=0.0001), initializer=tf.truncated_normal_initializer(stddev=1e-1, dtype=tf.float32)) #initializer=tf.contrib.layers.xavier_initializer(uniform=True)) conv = convolve(input_data, weights) biases = tf.get_variable( name="biases", shape=[c_o], dtype=tf.float32, initializer=tf.constant_initializer(value=0.0)) output = tf.nn.bias_add(conv, biases) if relu: output = tf.nn.relu(output, name=scope.name) return batch_norm(output)
def _LayerWithActivationProcessing(self, input_tensor=None, scope='test', post_activation_bypass=False): batch_size, height, width, depth = 5, 128, 128, 3 if input_tensor is None: input_tensor = array_ops.zeros((batch_size, height, width, depth)) weight_init = init_ops.truncated_normal_initializer with ops.name_scope(scope): output = layers.conv2d(input_tensor, depth, [5, 5], padding='SAME', weights_initializer=weight_init(0.09), activation_fn=None, normalizer_fn=None, biases_initializer=None) output = layers.batch_norm(output, center=True, scale=True, decay=1.0 - 0.003, fused=True) output = nn_ops.relu6(output) scaled_output1 = math_ops.mul(2.0, output) scaled_output2 = math_ops.mul(3.0, output) output = scaled_output1 + scaled_output2 return output
def _fully_connected(input_data, num_output, name, relu=True): with tf.variable_scope(name) as scope: input_shape = input_data.get_shape() if input_shape.ndims == 5: dim = 1 for d in input_shape[1:].as_list(): dim *= d feed_in = tf.reshape(input_data, [-1, dim]) else: feed_in, dim = (input_data, input_shape[-1].value) weights = tf.get_variable( name="weights", shape=[dim, num_output], regularizer=tf.contrib.layers.l2_regularizer(scale=0.0001), initializer=tf.truncated_normal_initializer(stddev=1e-1, dtype=tf.float32)) #initializer=tf.contrib.layers.xavier_initializer(uniform=True)) biases = tf.get_variable( name="biases", shape=[num_output], dtype=tf.float32, initializer=tf.constant_initializer(value=0.0)) op = tf.nn.relu_layer if relu else tf.nn.xw_plus_b output = op(feed_in, weights, biases, name=scope.name) return batch_norm(output)
def _LayerWithIdentity(self, input_tensor=None, scope='test', post_activation_bypass=False): """Add a basic conv, identity, batch norm with skip to the default graph.""" batch_size, height, width, depth = 5, 128, 128, 3 if input_tensor is None: input_tensor = array_ops.zeros((batch_size, height, width, depth)) weight_init = init_ops.truncated_normal_initializer with ops.name_scope(scope): output = layers.conv2d( input_tensor, depth, [5, 5], padding='SAME', weights_initializer=weight_init(0.09), activation_fn=None, normalizer_fn=None, biases_initializer=None) output = array_ops.identity(output, name='conv_out') output = layers.batch_norm( output, center=True, scale=True, decay=1.0 - 0.003, fused=True) output = array_ops.identity(output, name='bn_out') if post_activation_bypass: output += input_tensor return output
def adv_encode(inputs, is_training, reuse=False): with tf.variable_scope('loss', reuse=reuse): with arg_scope(resnet_arg_scope(is_training=is_training)): out = tf.nn.l2_normalize(inputs, axis=1) out = layers_lib.fully_connected(out, 128, activation_fn=None, biases_initializer=None) out = tf.stop_gradient(2 * out) - out out = layers.batch_norm(out, activation_fn=None) out = tf.nn.relu(out) out = layers_lib.fully_connected(out, 128, activation_fn=None) out = layers.batch_norm(out, activation_fn=None) out = tf.nn.l2_normalize(out, axis=1) return out
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)
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)
def batch_norm_layer(self, signal, scope): ''' 在激活之间批量归一化的层 :param signal: input signal :param scope: name scope :return: normalized signal ''' return tf.cond(self.is_training, lambda : batch_norm(signal, is_training=True, param_initializers={"beta": tf.constant_initializer(3.), "gamma": tf.constant_initializer(2,5)}, center=True, scale=True, activation_fn=tf.nn.relu, decay=1., scope=scope), lambda : batch_norm(signal, is_training=False, param_initializers={"beta": tf.constant_initializer(3.), "gamma": tf.constant_initializer(2,5)}, center=True, scale=True, activation_fn=tf.nn.relu, decay=1., scope=scope, reuse=True))
def batch_norm(x, is_training, decay=0.997, epsilon=1e-5, scale=True, center=True): normed = layers.batch_norm( x, decay=decay, epsilon=epsilon, is_training=is_training, center=center, scale=scale ) return normed
def batch_norm_layer(self, signal, scope): ''' batch normalization layer before activation :param signal: input signal :param scope: name scope :return: normalization signal ''' # 注意: is_training 是 tf.palceholder(tf.bool) 类型 # tf.cond 类似于c语言中的if...else...,用来控制数据流向 # Batch Normalization通过减少内部协变量加速神经网络的训练 return tf.cond(self.is_training, lambda : batch_norm(signal, is_training=True, param_initializers={"beta": tf.constant_initializer(3.), "gamma": tf.constant_initializer(2.5)}, center=True, scale=True, activation_fn=tf.nn.relu, decay=1, scope=scope), lambda : batch_norm(signal, is_training=False, param_initializers={"beta": tf.constant_initializer(3.), "gamma": tf.constant_initializer(2.5)}, center=True, scale=True, activation_fn=tf.nn.relu, decay=1, scope=scope, reuse=True))
def resnet50(image_input, is_training, embedding_dim, scope='resnet_v2_50', before_pool=False): with tf.variable_scope(scope): with arg_scope([layers.batch_norm], is_training=is_training, scale=True): with arg_scope([layers_lib.conv2d], activation_fn=None, normalizer_fn=None): out = conv2d_same(inputs=image_input, num_outputs=64, kernel_size=7, stride=2, scope='conv1') out = layers.max_pool2d(out, [3, 3], stride=2, scope='pool1') with arg_scope([layers_lib.conv2d], activation_fn=nn_ops.relu, normalizer_fn=layers.batch_norm): out = resnet_v2_block(inputs=out, base_depth=64, num_units=3, stride=2, scope='block1') out = resnet_v2_block(inputs=out, base_depth=128, num_units=4, stride=2, scope='block2') out = resnet_v2_block(inputs=out, base_depth=256, num_units=6, stride=2, scope='block3') out = resnet_v2_block(inputs=out, base_depth=512, num_units=3, stride=1, scope='block4') out = layers.batch_norm(out, activation_fn=nn_ops.relu, scope='postnorm') avg_out = tf.reduce_mean(out, axis=[1, 2], name='pool5') fc_out = tf.layers.dense(inputs=avg_out, units=embedding_dim) if before_pool: return out, fc_out else: return fc_out
def add_BN_conv_layer(inputs, kernalWidth, inDepth, outDepth, is_training_ph, scope , layername="layer", activateFunc=tf.nn.relu, stride=[1, 1, 1, 1]): # inDepth = inputs.get_shape().as_list()[3] with tf.name_scope(layername): Weights = tf.Variable(tf.truncated_normal([kernalWidth, kernalWidth, inDepth, outDepth], stddev=0.1)) biases = tf.Variable(tf.constant(0.1, tf.float32, [outDepth])) y1 = tf.nn.conv2d(inputs, Weights, stride, padding='SAME') + biases outputs = tf.cond(is_training_ph, lambda: batch_norm(y1,decay=0.94, is_training=True, center=False, scale=True, activation_fn=activateFunc, updates_collections=None, scope=scope), lambda: batch_norm(y1,decay=0.94, is_training=False, center=False, scale=True, activation_fn=activateFunc, updates_collections=None, scope=scope, reuse=True)) return outputs
def _conv_layer(self, bottom, name, shape, load=False, is_bn=True, train=True): with tf.variable_scope(name) as scope: filt = self.get_conv_filter(name, shape, load) conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME') conv_biases = self.get_bias(name, shape[3], load=load) bias = tf.nn.bias_add(conv, conv_biases) relu = tf.nn.relu(bias) # Add summary to Tensorboard # _activation_summary(relu) if (is_bn): # return utils.bn_layer(relu, is_training) return layers.batch_norm(relu, scope='afternorm', is_training=train) else: return relu
def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None): """Bottleneck residual unit variant with BN before convolutions.""" with variable_scope.variable_scope(scope, 'bottleneck_v2', [inputs]) as sc: depth_in = utils.last_dimension(inputs.get_shape(), min_rank=3) preact = layers.batch_norm(inputs, activation_fn=nn_ops.relu, scope='preact') if depth == depth_in: shortcut = subsample(inputs, stride, 'shortcut') else: shortcut = layers.convolution(preact, depth, 1, stride=stride, normalizer_fn=None, activation_fn=None, scope='shortcut') residual = layers.convolution(preact, depth_bottleneck, 1, stride=1, scope='conv1') residual = conv1d_same(residual, depth_bottleneck, 3, stride, rate=rate, scope='conv2') residual = layers.convolution(residual, depth, 1, stride=1, normalizer_fn=None, activation_fn=None, scope='conv3') output = shortcut + residual return utils.collect_named_outputs(outputs_collections, sc.name, output)
def resnet50(image_input, is_training, scope='resnet_v2_50'): with tf.variable_scope(scope): with arg_scope([layers.batch_norm], is_training=is_training, scale=True): with arg_scope([layers_lib.conv2d], activation_fn=None, normalizer_fn=None): out = conv2d(inputs=image_input, num_outputs=64, kernel_size=7, stride=2, scope='conv1') out = max_pool(inputs=out, kernel_size=3, stride=2, scope=scope) with arg_scope([layers_lib.conv2d], activation_fn=nn_ops.relu, normalizer_fn=layers.batch_norm): out = resnet_v2_block(inputs=out, base_depth=64, num_units=3, stride=2, scope='block1') out = resnet_v2_block(inputs=out, base_depth=128, num_units=4, stride=2, scope='block2') out = resnet_v2_block(inputs=out, base_depth=256, num_units=6, stride=2, scope='block3') out = resnet_v2_block(inputs=out, base_depth=512, num_units=3, stride=1, scope='block4') out = layers.batch_norm(out, activation_fn=nn_ops.relu, scope='postnorm') out = tf.reduce_mean(out, axis=[1, 2], name='pool5') out = tf.layers.dense(inputs=out, units=128) out = tf.nn.l2_normalize(out, axis=1) return out
def _upscore_layer(self, bottom, shape, num_classes, name, debug, ksize=4, stride=2,is_bn=True, train=True): strides = [1, stride, stride, 1] with tf.variable_scope(name): in_features = bottom.get_shape()[3].value if shape is None: # Compute shape out of Bottom in_shape = tf.shape(bottom) h = ((in_shape[1] - 1) * stride) + 1 w = ((in_shape[2] - 1) * stride) + 1 new_shape = [in_shape[0], h, w, num_classes] else: new_shape = [shape[0], shape[1], shape[2], num_classes] output_shape = tf.stack(new_shape) logging.debug("Layer: %s, Fan-in: %d" % (name, in_features)) f_shape = [ksize, ksize, num_classes, in_features] # create num_input = ksize * ksize * in_features / stride stddev = (2 / num_input)**0.5 weights = self.get_deconv_filter(f_shape) # weights = tf.Print(weights, [weights], # message='weights: ', # summarize=20, first_n=5) # self._add_wd_and_summary(weights, self.wd, "fc_wlosses") deconv = tf.nn.conv2d_transpose(bottom, weights, output_shape, strides=strides, padding='SAME') if debug: deconv = tf.Print(deconv, [tf.shape(deconv)], message='Shape of %s' % name, summarize=4, first_n=1) # _activation_summary(deconv) if (is_bn): # return utils.bn_layer(relu, is_training) return layers.batch_norm(deconv, scope='afternorm', is_training=train) else: return deconv
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)
def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1): with tf.variable_scope('bottleneck_v2'): 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 = max_pool(inputs=inputs, kernel_size=1, stride=stride, scope='shortcut') else: with arg_scope([layers_lib.conv2d], normalizer_fn=None, activation_fn=None): shortcut = conv2d(preact, depth, 1, stride=stride, scope='shortcut') residual = layers_lib.conv2d(preact, depth_bottleneck, 1, stride=1, scope='conv1') residual = conv2d(residual, depth_bottleneck, 3, stride, rate=rate, scope='conv2') residual = layers_lib.conv2d(residual, depth, 1, stride=1, normalizer_fn=None, activation_fn=None, scope='conv3') output = shortcut + residual return output
def conv_relu(input_, ksize, filter_num, name, activation=True): """ convolutional layer, with specific activation func and batch_normal """ with tf.variable_scope(name): if activation is True: _, h, w, d = input_.shape # _ is the batch size filter_shape = (ksize, ksize, input_.get_shape()[-1].value, filter_num) # filter_ = tf.Variable(np.zeros(filter_shape, dtype=np.float32)) filter_ = tf.get_variable('weights', filter_shape, tf.float32) # bias = tf.Variable(np.zeros(filter_num, dtype=np.float32)) bias = tf.get_variable('bias', filter_num, dtype=tf.float32) conv = tf.nn.conv2d(input_, filter_, strides=[1, 1, 1, 1], padding="SAME") conv = tf.nn.bias_add(conv, bias) if batch_normalization: btn = tf_ctb_layers.batch_norm(conv, scale=True) output = tf.nn.relu(btn) else: output = tf.nn.relu(conv) else: filter_shape = [ ksize, ksize, input_.get_shape()[-1].value, filter_num ] filter_ = tf.get_variable("weights", filter_shape, tf.float32) # filter_ = tf.Variable(np.zeros(filter_shape, dtype=np.float32)) output = tf.nn.conv2d(input_, filter_, strides=[1, 1, 1, 1], padding="SAME") logging.info("layer {0}, filter{1}, output{2}".format( name, filter_shape, output.shape)) return output
def deconv(input_, filter_num, factor, name): """ de-convolutional layer, tf.nn.using conv2d_transpose() Note: the op tf.nn.conv2d_transpose, consume the significant time. """ with tf.variable_scope(name): batch_size_, h, w, d = input_.shape # filter_shape = (h, w, d, filter_num) # filter_shape = (h, w, filter_num, d) filter_shape = (3, 3, filter_num, d) # filter_ = tf.Variable(np.zeros(filter_shape, dtype=np.float32)) filter_ = tf.get_variable('weights', filter_shape, tf.float32) # bias_ = tf.Variable(np.zeros(filter_num, dtype=np.float32)) bias_ = tf.get_variable('bias', filter_num) # output_shape_ = tf.stack([batch_size_, h * factor, w * factor, d]) output_shape_ = tf.TensorShape( [batch_size_, h * factor, w * factor, d]) deconv_ = tf.nn.conv2d_transpose(input_, filter_, output_shape=output_shape_, strides=[1, factor, factor, 1], padding="SAME") deconv_ = tf.nn.bias_add(deconv_, bias_) if batch_normalization: btn = tf_ctb_layers.batch_norm(deconv_, scale=True) output = tf.nn.relu(btn) else: output = tf.nn.relu(deconv_) logging.info("layer {0}, {1}".format(name, output.shape)) return output
def resnet50(image_input, is_training, scope='resnet_v2_50'): with tf.variable_scope(scope): with arg_scope(resnet_arg_scope(is_training=is_training)): with arg_scope([layers_lib.conv2d], activation_fn=None, normalizer_fn=None): out = conv2d_same(inputs=image_input, num_outputs=64, kernel_size=7, stride=2, scope='conv1') out = layers.max_pool2d(out, [3, 3], stride=2, scope='pool1') out = resnet_v2_block(inputs=out, base_depth=64, num_units=3, stride=2, scope='block1') out = resnet_v2_block(inputs=out, base_depth=128, num_units=4, stride=2, scope='block2') out = resnet_v2_block(inputs=out, base_depth=256, num_units=6, stride=2, scope='block3') out = resnet_v2_block(inputs=out, base_depth=512, num_units=3, stride=1, scope='block4') out = layers.batch_norm(out, activation_fn=nn_ops.relu, scope='postnorm') return out
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 batchnorm_classifier(inputs): inputs = layers.batch_norm(inputs, decay=0.1) return layers.fully_connected(inputs, 1, activation_fn=math_ops.sigmoid)
def f(x): x = convolutional.conv1d(x, self.CHANNELS // 2, 3, padding="same") x = layers.batch_norm(x, is_training=False) x = convolutional.conv1d(x, self.CHANNELS // 2, 3, padding="same") x = layers.batch_norm(x, is_training=False) return x
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
def BatchNormClassifier(inputs): inputs = layers.batch_norm(inputs, decay=0.1, fused=True) return layers.fully_connected(inputs, 1, activation_fn=math_ops.sigmoid)