def get_endpoints(self, x, nb_classes=None): with slim.arg_scope(self._model['arg_scope']()): # print("get_endpoints", self.name) logits, end_points = self._model['graph'](x, num_classes=self.nb_classes,is_training=False,reuse=tf.AUTO_REUSE) if 'Logits' not in end_points: end_points['Logits'] = logits if (len(end_points['Logits'].shape) == 4): end_points['Logits'] = tf.squeeze(end_points['Logits'] , [1,2]) if 'Predictions' not in end_points: end_points['Predictions'] = layers_lib.softmax(end_points['Logits'], scope='predictions') return end_points
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
def __call__(self, ens_x_input, vgg_x_input, inc_x_input, tcd_x_input): """Constructs model and return probabilities for given input.""" reuse = True if self.built else None logits = None aux_logits = None weights = [[0.7, 0.1], [0.2, 0.1]] all_inputs = [[ens_x_input, tcd_x_input], [inc_x_input, tcd_x_input]] scopes = [ inception_resnet_v2.inception_resnet_v2_arg_scope(), inception.inception_v3_arg_scope() ] reuse_flags = [reuse, True] for model_idx, model in enumerate( [inception_resnet_v2.inception_resnet_v2, inception.inception_v3]): with slim.arg_scope(scopes[model_idx]): for idx, inputs in enumerate(all_inputs[model_idx]): result = model(inputs, num_classes=self.num_classes, is_training=False, reuse=reuse_flags[idx]) weight = weights[model_idx][idx] # :1 is for slicing out the background class if logits == None: logits = result[0][:, 1:] * weight aux_logits = result[1]['AuxLogits'][:, 1:] * weight else: logits += result[0][:, 1:] * weight aux_logits += result[1]['AuxLogits'][:, 1:] * weight with slim.arg_scope(vgg.vgg_arg_scope()): weight = 0.1 result = vgg.vgg_16(vgg_x_input, num_classes=1000, is_training=False) logits += result[0] * weight with slim.arg_scope(resnet_utils.resnet_arg_scope()): weight = 0.05 result = resnet_v2.resnet_v2_152(vgg_x_input, num_classes=self.num_classes, reuse=reuse) logits += tf.squeeze(result[0])[:, 1:] * weight self.built = True aux_weight = 0.8 logits += aux_logits * aux_weight predictions = layers_lib.softmax(logits) return predictions
def resnet_v2( inputs, blocks, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, centered_stride=False, 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 = resnet_utils.max_pool2d_same( net, 3, stride=2, scope='pool1', centered_stride=centered_stride and output_stride == 4) 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 = slim.batch_norm(net, activation_fn=nn_ops.relu, scope='postnorm') if global_pool: # Global average pooling. net = math_ops.reduce_mean(net, tfu.image_axes(), name='pool5', keepdims=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 inception_v4(inputs, num_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionV4', create_aux_logits=True): """Creates the Inception V4 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer (before dropout) are returned instead. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. 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. create_aux_logits: Whether to include the auxiliary logits. Returns: net: a Tensor with the logits (pre-softmax activations) if num_classes is a non-zero integer, or the non-dropped input to the logits layer if num_classes is 0 or None. end_points: the set of end_points from the inception model. """ end_points = {} with variable_scope.variable_scope(scope, 'InceptionV4', [inputs], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = inception_v4_base(inputs, scope=scope) with slim.arg_scope( [slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # Auxiliary Head logits if create_aux_logits and num_classes: with variable_scope.variable_scope('AuxLogits'): # 17 x 17 x 1024 aux_logits = end_points['Mixed_6h'] aux_logits = slim.avg_pool2d(aux_logits, [5, 5], stride=3, padding='VALID', scope='AvgPool_1a_5x5') aux_logits = slim.conv2d(aux_logits, 128, [1, 1], scope='Conv2d_1b_1x1') aux_logits = slim.conv2d(aux_logits, 768, aux_logits.get_shape()[1:3], padding='VALID', scope='Conv2d_2a') aux_logits = slim.flatten(aux_logits) aux_logits = slim.fully_connected(aux_logits, num_classes, activation_fn=None, scope='Aux_logits') end_points['AuxLogits'] = aux_logits # Final pooling and prediction # TODO(sguada,arnoegw): Consider adding a parameter global_pool which # can be set to False to disable pooling here (as in resnet_*()). with variable_scope.variable_scope('Logits'): # 8 x 8 x 1536 kernel_size = net.get_shape()[1:3] if kernel_size.is_fully_defined(): net = slim.avg_pool2d(net, kernel_size, padding='VALID', scope='AvgPool_1a') else: net = math_ops.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool') end_points['global_pool'] = net if not num_classes: return net, end_points # 1 x 1 x 1536 net = slim.dropout(net, dropout_keep_prob, scope='Dropout_1b') net = slim.flatten(net, scope='PreLogitsFlatten') end_points['PreLogitsFlatten'] = net # 1536 logits = slim.fully_connected(net, num_classes, activation_fn=None, scope='Logits') end_points['Logits'] = logits end_points['Predictions'] = layers_lib.softmax( logits, scope='Predictions') return logits, end_points
def model_fn(features, labels, mode, params): """ Based on https://github.com/tensorflow/tpu/blob/master/models/experimental/inception/inception_v2_tpu_model.py :param features: :param labels: :param mode: :param params: :return: """ tf.summary.image('0_input', features, max_outputs=4) training = mode == tf.estimator.ModeKeys.TRAIN # 224 x 224 x 3 end_point = 'Conv2d_1a_7x7' net = layers.conv2d(features, 64, [7, 7], stride=2, weights_initializer=trunc_normal(1.0), activation_fn=None, scope=end_point) net = tf.layers.batch_normalization(net, training=training, name='{}_bn'.format(end_point)) net = tf.nn.relu(net, name='{}_act'.format(end_point)) tf.summary.image('1_{}'.format(end_point), net[:, :, :, 0:3], max_outputs=4) # 112 x 112 x 64 end_point = 'MaxPool_2a_3x3' net = layers_lib.max_pool2d(net, [3, 3], scope=end_point, stride=2, padding='SAME') tf.summary.image('2_{}'.format(end_point), net[:, :, :, 0:3], max_outputs=4) # 56 x 56 x 64 end_point = 'Conv2d_2b_1x1' net = layers.conv2d(net, 64, [1, 1], activation_fn=None, scope=end_point, weights_initializer=trunc_normal(0.1)) net = tf.layers.batch_normalization(net, training=training, name='{}_bn'.format(end_point)) net = tf.nn.relu(net, name='{}_act'.format(end_point)) tf.summary.image('3_{}'.format(end_point), net[:, :, :, 0:3], max_outputs=4) # 56 x 56 x 64 end_point = 'Conv2d_2c_3x3' net = layers.conv2d(net, 192, [3, 3], activation_fn=None, scope=end_point) net = tf.layers.batch_normalization(net, training=training, name='{}_bn'.format(end_point)) net = tf.nn.relu(net, name='{}_act'.format(end_point)) tf.summary.image('4_{}'.format(end_point), net[:, :, :, 0:3], max_outputs=4) # 56 x 56 x 192 end_point = 'MaxPool_3a_3x3' net = layers_lib.max_pool2d(net, [3, 3], scope=end_point, stride=2, padding='SAME') tf.summary.image('5_{}'.format(end_point), net[:, :, :, 0:3], max_outputs=4) # 28 x 28 x 192 # Inception module. end_point = 'Mixed_3b' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d(net, 64, [1, 1], activation_fn=None, scope='Conv2d_0a_1x1') branch_0 = tf.layers.batch_normalization(branch_0, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_0 = tf.nn.relu(branch_0, name='{}_act'.format('Conv2d_0a_1x1')) with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d(net, 64, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0a_1x1')) branch_1 = layers.conv2d(branch_1, 64, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0b_3x3')) with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d(net, 64, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0a_1x1')) branch_2 = layers.conv2d(branch_2, 96, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0b_3x3')) branch_2 = layers.conv2d(branch_2, 96, [3, 3], activation_fn=None, scope='Conv2d_0c_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0c_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0c_3x3')) with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], padding='SAME', stride=1, scope='AvgPool_0a_3x3') branch_3 = layers.conv2d(branch_3, 32, [1, 1], weights_initializer=trunc_normal(0.1), activation_fn=None, scope='Conv2d_0b_1x1') branch_3 = tf.layers.batch_normalization(branch_3, training=training, name='{}_bn'.format('Conv2d_0b_1x1')) branch_3 = tf.nn.relu(branch_3, name='{}_act'.format('Conv2d_0b_1x1')) net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) # 28 x 28 x 256 end_point = 'Mixed_3c' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d(net, 64, [1, 1], activation_fn=None, scope='Conv2d_0a_1x1') branch_0 = tf.layers.batch_normalization(branch_0, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_0 = tf.nn.relu(branch_0, name='{}_act'.format('Conv2d_0a_1x1')) with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d(net, 64, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0a_1x1')) branch_1 = layers.conv2d(branch_1, 96, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0b_3x3')) with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d(net, 64, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0a_1x1')) branch_2 = layers.conv2d(branch_2, 96, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0b_3x3')) branch_2 = layers.conv2d(branch_2, 96, [3, 3], activation_fn=None, scope='Conv2d_0c_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0c_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0c_3x3')) with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], padding='SAME', stride=1, scope='AvgPool_0a_3x3') branch_3 = layers.conv2d(branch_3, 64, [1, 1], weights_initializer=trunc_normal(0.1), activation_fn=None, scope='Conv2d_0b_1x1') branch_3 = tf.layers.batch_normalization(branch_3, training=training, name='{}_bn'.format('Conv2d_0b_1x1')) branch_3 = tf.nn.relu(branch_3, name='{}_act'.format('Conv2d_0b_1x1')) net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) # 28 x 28 x 320 end_point = 'Mixed_4a' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d(net, 128, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_0 = tf.layers.batch_normalization(branch_0, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_0 = tf.nn.relu(branch_0, name='{}_act'.format('Conv2d_0a_1x1')) branch_0 = layers.conv2d(branch_0, 160, [3, 3], stride=2, activation_fn=None, scope='Conv2d_1a_3x3') branch_0 = tf.layers.batch_normalization(branch_0, training=training, name='{}_bn'.format('Conv2d_1a_3x3')) branch_0 = tf.nn.relu(branch_0, name='{}_act'.format('Conv2d_1a_3x3')) with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d(net, 64, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0a_1x1')) branch_1 = layers.conv2d(branch_1, 96, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0b_3x3')) branch_1 = layers.conv2d(branch_1, 96, [3, 3], stride=2, activation_fn=None, scope='Conv2d_1a_3x3') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_1a_3x3')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_1a_3x3')) with variable_scope.variable_scope('Branch_2'): branch_2 = layers_lib.max_pool2d(net, [3, 3], stride=2, padding='SAME', scope='MaxPool_1a_3x3') net = array_ops.concat([branch_0, branch_1, branch_2], 3) # 14 x 14 x 576 end_point = 'Mixed_4b' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d(net, 224, [1, 1], activation_fn=None, scope='Conv2d_0a_1x1') branch_0 = tf.layers.batch_normalization(branch_0, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_0 = tf.nn.relu(branch_0, name='{}_act'.format('Conv2d_0a_1x1')) with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d(net, 64, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0a_1x1')) branch_1 = layers.conv2d(branch_1, 96, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0b_3x3')) with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d(net, 96, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0a_1x1')) branch_2 = layers.conv2d(branch_2, 128, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0b_3x3')) branch_2 = layers.conv2d(branch_2, 128, [3, 3], activation_fn=None, scope='Conv2d_0c_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0c_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0c_3x3')) with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], padding='SAME', stride=1, scope='AvgPool_0a_3x3') branch_3 = layers.conv2d(branch_3, 128, [1, 1], weights_initializer=trunc_normal(0.1), activation_fn=None, scope='Conv2d_0b_1x1') branch_3 = tf.layers.batch_normalization(branch_3, training=training, name='{}_bn'.format('Conv2d_0b_1x1')) branch_3 = tf.nn.relu(branch_3, name='{}_act'.format('Conv2d_0b_1x1')) net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) # 14 x 14 x 576 end_point = 'Mixed_4c' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d(net, 192, [1, 1], activation_fn=None, scope='Conv2d_0a_1x1') branch_0 = tf.layers.batch_normalization(branch_0, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_0 = tf.nn.relu(branch_0, name='{}_act'.format('Conv2d_0a_1x1')) with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d(net, 96, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0a_1x1')) branch_1 = layers.conv2d(branch_1, 128, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0b_3x3')) with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d(net, 96, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0a_1x1')) branch_2 = layers.conv2d(branch_2, 128, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0b_3x3')) branch_2 = layers.conv2d(branch_2, 128, [3, 3], activation_fn=None, scope='Conv2d_0c_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0c_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0c_3x3')) with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], padding='SAME', stride=1, scope='AvgPool_0a_3x3') branch_3 = layers.conv2d(branch_3, 128, [1, 1], weights_initializer=trunc_normal(0.1), activation_fn=None, scope='Conv2d_0b_1x1') branch_3 = tf.layers.batch_normalization(branch_3, training=training, name='{}_bn'.format('Conv2d_0b_1x1')) branch_3 = tf.nn.relu(branch_3, name='{}_act'.format('Conv2d_0b_1x1')) net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) # 14 x 14 x 576 end_point = 'Mixed_4d' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d(net, 160, [1, 1], activation_fn=None, scope='Conv2d_0a_1x1') branch_0 = tf.layers.batch_normalization(branch_0, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_0 = tf.nn.relu(branch_0, name='{}_act'.format('Conv2d_0a_1x1')) with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d(net, 128, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0a_1x1')) branch_1 = layers.conv2d(branch_1, 160, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0b_3x3')) with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d(net, 128, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0a_1x1')) branch_2 = layers.conv2d(branch_2, 160, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0b_3x3')) branch_2 = layers.conv2d(branch_2, 160, [3, 3], activation_fn=None, scope='Conv2d_0c_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0c_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0c_3x3')) with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], padding='SAME', stride=1, scope='AvgPool_0a_3x3') branch_3 = layers.conv2d(branch_3, 96, [1, 1], weights_initializer=trunc_normal(0.1), activation_fn=None, scope='Conv2d_0b_1x1') branch_3 = tf.layers.batch_normalization(branch_3, training=training, name='{}_bn'.format('Conv2d_0b_1x1')) branch_3 = tf.nn.relu(branch_3, name='{}_act'.format('Conv2d_0b_1x1')) net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) # 14 x 14 x 576 end_point = 'Mixed_4e' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d(net, 96, [1, 1], activation_fn=None, scope='Conv2d_0a_1x1') branch_0 = tf.layers.batch_normalization(branch_0, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_0 = tf.nn.relu(branch_0, name='{}_act'.format('Conv2d_0a_1x1')) with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d(net, 128, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0a_1x1')) branch_1 = layers.conv2d(branch_1, 192, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0b_3x3')) with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d(net, 160, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0a_1x1')) branch_2 = layers.conv2d(branch_2, 192, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0b_3x3')) branch_2 = layers.conv2d(branch_2, 192, [3, 3], activation_fn=None, scope='Conv2d_0c_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0c_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0c_3x3')) with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], padding='SAME', stride=1, scope='AvgPool_0a_3x3') branch_3 = layers.conv2d(branch_3, 96, [1, 1], weights_initializer=trunc_normal(0.1), activation_fn=None, scope='Conv2d_0b_1x1') branch_3 = tf.layers.batch_normalization(branch_3, training=training, name='{}_bn'.format('Conv2d_0b_1x1')) branch_3 = tf.nn.relu(branch_3, name='{}_act'.format('Conv2d_0b_1x1')) net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) # 14 x 14 x 576 end_point = 'Mixed_5a' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d(net, 128, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_0 = tf.layers.batch_normalization(branch_0, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_0 = tf.nn.relu(branch_0, name='{}_act'.format('Conv2d_0a_1x1')) branch_0 = layers.conv2d(branch_0, 192, [3, 3], stride=2, activation_fn=None, scope='Conv2d_1a_3x3') branch_0 = tf.layers.batch_normalization(branch_0, training=training, name='{}_bn'.format('Conv2d_1a_3x3')) branch_0 = tf.nn.relu(branch_0, name='{}_act'.format('Conv2d_1a_3x3')) with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d(net, 192, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0a_1x1')) branch_1 = layers.conv2d(branch_1, 256, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0b_3x3')) branch_1 = layers.conv2d(branch_1, 256, [3, 3], stride=2, activation_fn=None, scope='Conv2d_1a_3x3') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_1a_3x3')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_1a_3x3')) with variable_scope.variable_scope('Branch_2'): branch_2 = layers_lib.max_pool2d(net, [3, 3], stride=2, padding='SAME', scope='MaxPool_1a_3x3') net = array_ops.concat([branch_0, branch_1, branch_2], 3) # 7 x 7 x 1024 end_point = 'Mixed_5b' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d(net, 352, [1, 1], activation_fn=None, scope='Conv2d_0a_1x1') branch_0 = tf.layers.batch_normalization(branch_0, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_0 = tf.nn.relu(branch_0, name='{}_act'.format('Conv2d_0a_1x1')) with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d(net, 192, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0a_1x1')) branch_1 = layers.conv2d(branch_1, 320, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0b_3x3')) with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d(net, 160, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0a_1x1')) branch_2 = layers.conv2d(branch_2, 224, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0b_3x3')) branch_2 = layers.conv2d(branch_2, 224, [3, 3], activation_fn=None, scope='Conv2d_0c_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0c_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0c_3x3')) with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], padding='SAME', stride=1, scope='AvgPool_0a_3x3') branch_3 = layers.conv2d(branch_3, 128, [1, 1], weights_initializer=trunc_normal(0.1), activation_fn=None, scope='Conv2d_0b_1x1') branch_3 = tf.layers.batch_normalization(branch_3, training=training, name='{}_bn'.format('Conv2d_0b_1x1')) branch_3 = tf.nn.relu(branch_3, name='{}_act'.format('Conv2d_0b_1x1')) net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) # 7 x 7 x 1024 end_point = 'Mixed_5c' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d(net, 352, [1, 1], activation_fn=None, scope='Conv2d_0a_1x1') branch_0 = tf.layers.batch_normalization(branch_0, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_0 = tf.nn.relu(branch_0, name='{}_act'.format('Conv2d_0a_1x1')) with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d(net, 192, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0a_1x1')) branch_1 = layers.conv2d(branch_1, 320, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_1 = tf.layers.batch_normalization(branch_1, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_1 = tf.nn.relu(branch_1, name='{}_act'.format('Conv2d_0b_3x3')) with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d(net, 192, [1, 1], weights_initializer=trunc_normal(0.09), activation_fn=None, scope='Conv2d_0a_1x1') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0a_1x1')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0a_1x1')) branch_2 = layers.conv2d(branch_2, 224, [3, 3], activation_fn=None, scope='Conv2d_0b_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0b_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0b_3x3')) branch_2 = layers.conv2d(branch_2, 224, [3, 3], activation_fn=None, scope='Conv2d_0c_3x3') branch_2 = tf.layers.batch_normalization(branch_2, training=training, name='{}_bn'.format('Conv2d_0c_3x3')) branch_2 = tf.nn.relu(branch_2, name='{}_act'.format('Conv2d_0c_3x3')) with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.max_pool2d(net, [3, 3], padding='SAME', stride=1, scope='MaxPool_0a_3x3') branch_3 = layers.conv2d(branch_3, 128, [1, 1], weights_initializer=trunc_normal(0.1), activation_fn=None, scope='Conv2d_0b_1x1') branch_3 = tf.layers.batch_normalization(branch_3, training=training, name='{}_bn'.format('Conv2d_0b_1x1')) branch_3 = tf.nn.relu(branch_3, name='{}_act'.format('Conv2d_0b_1x1')) net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) with variable_scope.variable_scope('Logits'): kernel_size = util._reduced_kernel_size_for_small_input(net, [7, 7]) net = layers_lib.avg_pool2d(net, kernel_size, stride=1, padding='VALID', scope='AvgPool_1a_{}x{}'.format(*kernel_size)) # 1 x 1 x 1024 net = layers_lib.dropout(net, keep_prob=params['dropout_keep_prob'], scope='Dropout_1b') logits = layers.conv2d(net, params['num_classes'], [1, 1], normalizer_fn=None, activation_fn=None, scope='Conv2d_1c_1x1') if params['spatial_squeeze']: logits = array_ops.squeeze(logits, [1, 2], name='SpatialSqueeze') predictions = { 'argmax': tf.argmax(logits, axis=1, name='prediction_classes'), 'predictions': layers_lib.softmax(logits, scope='Predictions'), } if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) loss = tf.losses.sparse_softmax_cross_entropy(logits=logits, labels=labels) tf.summary.scalar('loss', loss) eval_metric_ops = { 'accuracy_val': tf.metrics.accuracy(labels=labels, predictions=predictions['argmax']) } if mode == tf.estimator.ModeKeys.EVAL: return tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops) optimizer = tf.train.GradientDescentOptimizer(learning_rate=params['learning_rate']) extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(extra_update_ops): train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step()) tf.summary.scalar('accuracy_train', eval_metric_ops['accuracy_val'][1]) tf.summary.histogram('labels', labels) tf.summary.histogram('predictions', predictions['argmax']) return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)
def Unet(x, labels, keep_prob=1.0, channels=3, n_class=2, num_layers=5, features_root=64, filter_size=3, pool_size=2, summaries=True, trainable=True, reuse=False, scope='dis'): with tf.variable_scope(scope, reuse=reuse): print(scope) end_points = {} logging.info( "Layers {layers}, features {features}, filter size {filter_size}x{filter_size}, pool size: {pool_size}x{pool_size}" .format(layers=layers, features=features_root, filter_size=filter_size, pool_size=pool_size)) # Placeholder for the input image with tf.name_scope("preprocessing"): batch_size = tf.shape(x)[0] nx = tf.shape(x)[1] ny = tf.shape(x)[2] in_node = x in_size = 1000 size = in_size # down layers logits = conv(in_node, 16, kernel=3, stride=1, pad=0, pad_type='zero', scope='conv_11') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = conv(logits, 32, kernel=3, stride=1, pad=0, pad_type='zero', scope='conv_12') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = max_pool(logits, pool_size) logits = conv(logits, 64, kernel=3, stride=1, pad=0, pad_type='zero', scope='conv_21') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = conv(logits, 64, kernel=3, stride=1, pad=0, pad_type='zero', scope='conv_22') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = max_pool(logits, pool_size) logits = conv(logits, 128, kernel=3, stride=1, pad=0, pad_type='zero', scope='conv_31') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = conv(logits, 128, kernel=3, stride=1, pad=0, pad_type='zero', scope='conv_32') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = max_pool(logits, pool_size) logits = conv(logits, 256, kernel=3, stride=1, pad=0, pad_type='zero', scope='conv_41') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = conv(logits, 256, kernel=3, stride=1, pad=0, pad_type='zero', scope='conv_42') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = max_pool(logits, pool_size) logits = conv(logits, 512, kernel=3, stride=1, pad=0, pad_type='zero', scope='conv_51') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = conv(logits, 256, kernel=3, stride=1, pad=0, pad_type='zero', scope='deconv_1') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = up_sample_bilinear(logits, scale_factor=2) logits = conv(logits, 256, kernel=3, stride=1, pad=0, pad_type='zero', scope='deconv_21') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = conv(logits, 128, kernel=3, stride=1, pad=0, pad_type='zero', scope='deconv_22') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = up_sample_bilinear(logits, scale_factor=2) logits = conv(logits, 128, kernel=4, stride=1, pad=0, pad_type='zero', scope='deconv_31') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = conv(logits, 128, kernel=3, stride=1, pad=0, pad_type='zero', scope='deconv_32') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = up_sample_bilinear(logits, scale_factor=2) logits = conv(logits, 64, kernel=3, stride=1, pad=0, pad_type='zero', scope='deconv_41') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = conv(logits, 32, kernel=3, stride=1, pad=0, pad_type='zero', scope='deconv_42') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) logits = up_sample_bilinear(logits, scale_factor=2) logits = conv(logits, 16, kernel=3, stride=1, pad=0, pad_type='zero', scope='deconv_51') logits = tf_contrib.layers.batch_norm(logits, decay=0.9, epsilon=1e-05, center=True, scale=True, is_training=trainable) logits = tf.nn.relu(logits) output_map = conv(logits, 1, kernel=3, stride=1, pad=0, pad_type='zero', scope='output') end_points['Logits'] = output_map end_points['Predictions'] = layers.softmax(output_map, scope='predictions') end_points['offset'] = layers.softmax(output_map, scope='predictions') return output_map, end_points
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 _tower_loss(network_fn, images, labels, is_cross=True, reuse=False, is_training=False): """Calculate the total loss on a single tower running the reid model.""" scale = 64. scale_pred = 4. margin = 0.5 net_features, net_logits, net_endpoints, net_raw_loss, net_pred, net_features, c_update_op = {}, {}, {}, {}, {}, {}, {} weight_loss, net_regularization, net_pred, net_predict = {}, {}, {}, {} for i in range(FLAGS.num_networks): net_features["{0}".format(i)], net_endpoints["{0}".format(i)] = \ network_fn["{0}".format(i)](images, reuse=reuse, is_training=is_training, scope=('dmlnet_%d' % i)) if is_cross: net_predict["{0}".format(i)], net_logits["{0}".format( i)], net_regularization["{0}".format(i)], weight, c_update_op[ "{0}".format(i)] = DA_loss(net_features["{0}".format(i)], tf.argmax(labels, axis=1), FLAGS.num_classes, s=scale, m=margin, scope=('dmlnet_%d' % i), is_cross=is_cross, reuse=reuse) net_raw_loss["{0}".format(i)] = tf.losses.softmax_cross_entropy( logits=net_logits["{0}".format(i)], onehot_labels=labels, label_smoothing=FLAGS.label_smoothing, weights=1.0) + tf.reduce_mean(weight) kl_weight = 1.0 else: print('semi_data!') net_predict["{0}".format(i)], _, _, _, _ = DA_loss( net_features["{0}".format(i)], tf.argmax(labels, axis=1), FLAGS.num_classes, s=scale, m=margin, scope=('dmlnet_%d' % i), is_cross=is_cross, reuse=reuse) net_pred["{0}".format(i)] = layers.softmax( scale_pred * net_predict["{0}".format(i)], scope='predictions') ## if the maximum probability of semi data is larger than threshold, update the feature centers. softmax_logits = net_pred["{0}".format(i)] ones = array_ops.ones_like(softmax_logits, dtype=softmax_logits.dtype) zeros = array_ops.zeros_like(softmax_logits, dtype=softmax_logits.dtype) threshold = 0.7 * array_ops.ones_like( softmax_logits, dtype=softmax_logits.dtype) #threshold is set as 0.85 threshold_softmax_logits = array_ops.where( softmax_logits > threshold, ones, zeros) threshold_softmax_logits = tf.reduce_max(threshold_softmax_logits, axis=-1) idx = tf.where(threshold_softmax_logits > 0.95) feats = tf.gather_nd(net_endpoints["{0}".format(i)]['feature'], idx) argmax_logits = tf.gather_nd(tf.argmax(softmax_logits, axis=1), idx) _, _, _, _, c_update_op["{0}".format(i)] = DA_loss( feats, argmax_logits, FLAGS.num_classes, s=scale, m=margin, scope=('dmlnet_%d' % i), is_cross=True, reuse=reuse) net_raw_loss["{0}".format(i)] = tf.constant(0.0) net_regularization["{0}".format(i)] = tf.constant(0.0) kl_weight = 1.0 if i == 0: attention0 = net_endpoints["{0}".format(i)]['attention0'] attention1 = net_endpoints["{0}".format(i)]['attention1'] #images = 0.5 * (images + 0.5 * images * attention0 + 0.5 * images * attention1) images = (images + images * attention0 + images * attention1) / 3.0 # Add KL loss if there are more than one network net_loss, kl_loss, net_reg_loss, net_total_loss, net_loss_averages, net_loss_averages_op = {}, {}, {}, {}, {}, {} for i in range(FLAGS.num_networks): net_pred["{0}".format(i)] = layers.softmax( scale_pred * net_predict["{0}".format(i)], scope='predictions') for i in range(FLAGS.num_networks): net_loss["{0}".format(i)] = net_raw_loss["{0}".format( i)] + net_regularization["{0}".format(i)] for j in range(FLAGS.num_networks): if i != j: kl_loss["{0}{0}".format(i, j)] = JS_loss_compute( net_pred["{0}".format(i)], net_pred["{0}".format(j)]) net_loss["{0}".format( i)] += kl_weight * kl_loss["{0}{0}".format(i, j)] #tf.summary.scalar('kl_loss_%d%d' % (i, j), kl_loss["{0}{0}".format(i, j)]) net_reg_loss["{0}".format(i)] = tf.add_n([ FLAGS.weight_decay * tf.nn.l2_loss(var) for var in tf.trainable_variables() if 'dmlnet_%d' % i in var.name ]) net_total_loss["{0}".format( i)] = net_loss["{0}".format(i)] + net_reg_loss["{0}".format(i)] return net_total_loss, c_update_op, net_pred, attention0, attention1, images
def Unet(x, labels, keep_prob=1.0, channels=3, n_class=2, num_layers=5, features_root=64, filter_size=3, pool_size=2,summaries=True, trainable=True, reuse=False, scope='dis'): with tf.variable_scope(scope, reuse=reuse): print(scope) #if scope == 'dmlnet_0': weight_init = tf.random_normal_initializer(mean=0.0, stddev=0.1) #if scope == 'dmlnet_1': # weight_init = tf.random_normal_initializer(mean=0.0, stddev=0.15) end_points = {} logging.info( "Layers {num_layers}, features {features}, filter size {filter_size}x{filter_size}, pool size: {pool_size}x{pool_size}".format( num_layers=num_layers, features=features_root, filter_size=filter_size, pool_size=pool_size)) # Placeholder for the input image #with tf.variable_scope("preprocessing", reuse=reuse): batch_size = tf.shape(x)[0] nx = tf.shape(x)[1] ny = tf.shape(x)[2] in_node = x weights = [] biases = [] convs = [] pools = OrderedDict() deconv = OrderedDict() dw_h_convs = OrderedDict() up_h_convs = OrderedDict() in_size = 1000 size = in_size # down layers for layer in range(0, num_layers): with tf.variable_scope("down_conv_{}".format(str(layer)), reuse=reuse): features = 2 ** layer * features_root conv1 = atrous_conv2d(in_node, features, kernel=3, rate=1, pad=0, pad_type='zero', scope='atrous1') conv2 = atrous_conv2d(in_node, features, kernel=3, rate=2, pad=0, pad_type='zero', scope='atrous2') conv3 = atrous_conv2d(in_node, features, kernel=3, rate=3, pad=0, pad_type='zero', scope='atrous3') gamma1 = tf.get_variable("GGamma1", [1], initializer=tf.constant_initializer(1/3.0)) gamma2 = tf.get_variable("GGamma2", [1], initializer=tf.constant_initializer(1/3.0)) gamma3 = tf.get_variable("GGamma3", [1], initializer=tf.constant_initializer(1/3.0)) '''tf.summary.scalar("down_conv_%d" % layer + '/gamma1', gamma1) tf.summary.scalar("down_conv_%d" % layer + '/gamma2', gamma2) tf.summary.scalar("down_conv_%d" % layer + '/gamma3', gamma3)''' conv = gamma1*conv1 + gamma2*conv2 + gamma3*conv3 conv = tf_contrib.layers.batch_norm(conv,decay=0.9, epsilon=1e-05,center=True, scale=True, updates_collections=None,is_training=trainable) conv = tf.nn.relu(conv) size -= 4 #if layer < num_layers - 1: pools[layer] = max_pool(conv, pool_size) in_node = pools[layer] size /= 2 dw_h_convs[layer] = in_node print('down_conv',layer, dw_h_convs[layer]) in_node = dw_h_convs[num_layers - 1] # up layers for layer in range(num_layers - 1, -1, -1): with tf.variable_scope("up_conv_{}".format(str(layer)), reuse=reuse): features = 2 ** (layer) * features_root stddev = np.sqrt(2 / (filter_size ** 2 * features)) if layer != 0 and layer != 1: wd = weight_variable_devonc([pool_size, pool_size, features, features// 2], stddev, weight_init, name="wd") bd = bias_variable([features // 2], weight_init, name="bd") if layer == 0 or layer == 1: wd = weight_variable_devonc([pool_size, pool_size, features, features], stddev, weight_init, name="wd") bd = bias_variable([features], weight_init, name="bd") #h_deconv = tf.nn.relu(deconv2d(in_node, wd, pool_size,reuse=reuse) + bd) in_node = up_sample_bilinear(in_node, scale_factor=2) h_deconv = tf.nn.relu(conv2d(in_node, wd, bd, keep_prob,reuse=reuse)) ###################### if layer != 0 and layer != 1: #h_deconv_concat, offset1 = deform_conv2d(h_deconv, dw_h_convs[layer], offset_kernel_size=3, kernel_size=3, num_outputs=features// 2, activation=tf.nn.relu, scope="adaptive_conv", reuse=reuse) print('h_deconv',layer, h_deconv) print('dw_h_convs[layer]',dw_h_convs[layer-1]) h_deconv_concat, offset1 = adaptive_deform_con2v(h_deconv, dw_h_convs[layer-1], features// 2, kernel_size=3, stride=1, trainable=trainable, name='adaptive_conv', reuse=reuse) end_points['offset'+str(layer)] = offset1 h_deconv_concat = tf.concat([h_deconv_concat, h_deconv],axis=-1) ###################### if layer == 0 or layer == 1: #h_deconv_concat = atrous_conv2d(dw_h_convs[layer], features// 2, kernel=3, rate=2, pad=0, pad_type='zero', scope='atrous_conv') #h_deconv_concat = tf.concat([dw_h_convs[layer], h_deconv],axis=-1) h_deconv_concat = h_deconv deconv[layer] = h_deconv_concat print('h_deconv_concat',h_deconv_concat) if layer != 0: conv1 = atrous_conv2d(h_deconv_concat, features//2, kernel=3, rate=1, pad=0, pad_type='zero', scope='atrous1') conv2 = atrous_conv2d(h_deconv_concat, features//2, kernel=3, rate=2, pad=0, pad_type='zero', scope='atrous2') conv3 = atrous_conv2d(h_deconv_concat, features//2, kernel=3, rate=3, pad=0, pad_type='zero', scope='atrous3') #if layer == 0: # conv1 = atrous_conv2d(h_deconv_concat, features, kernel=features, rate=1, pad=0, pad_type='zero', scope='atrous1') # conv2 = atrous_conv2d(h_deconv_concat, features, kernel=features, rate=2, pad=0, pad_type='zero', scope='atrous2') # conv3 = atrous_conv2d(h_deconv_concat, features, kernel=features, rate=3, pad=0, pad_type='zero', scope='atrous3') beta1 = tf.get_variable("GGammaalphabeta1", [1], initializer=tf.constant_initializer(1/3.0)) beta2 = tf.get_variable("GGammaalphabeta2", [1], initializer=tf.constant_initializer(1/3.0)) beta3 = tf.get_variable("GGammaalphabeta3", [1], initializer=tf.constant_initializer(1/3.0)) '''tf.summary.scalar("up_conv_%d" % layer + '/alphabeta1', beta1) tf.summary.scalar("up_conv_%d" % layer + '/alphabeta2', beta2) tf.summary.scalar("up_conv_%d" % layer + '/alphabeta3', beta3)''' conv = beta1*conv1 + beta2*conv2 + beta3*conv3 conv = tf_contrib.layers.batch_norm(conv,decay=0.9, epsilon=1e-05,center=True, scale=True, updates_collections=None,is_training=trainable) in_node = tf.nn.relu(conv) up_h_convs[layer] = in_node print('up_h_convs[layer]',up_h_convs[layer]) size *= 2 size -= 4 # Output Map #with tf.variable_scope("output_map", reuse=reuse): weight = weight_variable([1, 1, features_root, n_class], stddev, weight_init, name = 'out_w') bias = bias_variable([n_class], weight_init, name="bias") conv = conv2d(in_node, weight, bias, tf.constant(1.0),reuse=reuse) #output_map = tf.nn.relu(conv) output_map = conv print(output_map) #up_h_convs["out"] = output_map '''if summaries: with tf.name_scope("summaries"): for i, (c1, c2) in enumerate(convs): tf.summary.image('summary_conv_%02d_01' % i, get_image_summary(c1)) tf.summary.image('summary_conv_%02d_02' % i, get_image_summary(c2)) for k in pools.keys(): tf.summary.image('summary_pool_%02d' % k, get_image_summary(pools[k])) for k in deconv.keys(): tf.summary.image('summary_deconv_concat_%02d' % k, get_image_summary(deconv[k])) ''''''for k in dw_h_convs.keys(): #tf.summary.histogram("dw_convolution_%02d" % k + '/activations', dw_h_convs[k]) tf.summary.scalar("down_conv_%d" % k + '/gamma1', gamma1) tf.summary.scalar("down_conv_%d" % k + '/gamma2', gamma2) tf.summary.scalar("down_conv_%d" % k + '/gamma3', gamma3) for k in up_h_convs.keys(): #tf.summary.histogram("up_convolution_%s" % k + '/activations', up_h_convs[k]) tf.summary.scalar("up_conv_%d" % k + '/alphabeta1', beta1) tf.summary.scalar("up_conv_%d" % k + '/alphabeta2', beta2) tf.summary.scalar("up_conv_%d" % k + '/alphabeta3', beta3)'''''' tf.summary.image("out" , get_image_summary(tf.expand_dims(tf.argmax(output_map,-1),-1))) tf.summary.image("label" , get_image_summary(tf.expand_dims(tf.argmax(labels,-1),-1))) tf.summary.image("offset" , get_image_summary(offset1)) tf.summary.image("input" , tf.expand_dims(x[0,:,:,:],0))''' variables = [] for w1, w2 in weights: variables.append(w1) variables.append(w2) for b1, b2 in biases: variables.append(b1) variables.append(b2) end_points['Logits'] = output_map end_points['Predictions'] = layers.softmax(output_map, scope='predictions') return output_map,end_points
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, isFetchDictForDebug=False, # added by CCJ for code debugging!!! ): """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. """ fetch_dict = {} with variable_scope.variable_scope(scope, 'resnet_v2', [inputs], reuse=reuse) as sc: """ Comments added by CCJ: here 'resnet_v2' is default_name, in case the 'scope' is None. If `scope` here is provided, then the default name won't be used. """ 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') fetch_dict['x_conv1'] = net # added by CCJ; # updated by CCJ: #> see:https://www.corvil.com/kb/what-is-the-difference-between-same-and-valid-padding-in-tf-nn-max-pool-of-tensorflow net = layers.max_pool2d(net, [3, 3], stride=2, scope='pool1') #net = layers.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='pool1') # 'VALID' is not default; #net = layers.max_pool2d(net, [3, 3], stride=2, padding='SAME', scope='pool1') #'SAME' is by default; fetch_dict['x_maxpool'] = net # added by CCJ; net = resnet_utils.stack_blocks_dense(net, blocks, output_stride) fetch_dict['x_layer4'] = net # added by CCJ; # 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') fetch_dict['x_postnorm'] = net if global_pool: # Global average pooling. net = math_ops.reduce_mean( net, [ 1, 2 ], # the dimensions to reduce, here [1,2] means H and W dimension, due to NHWC format; name='pool5', #keep_dims=True, #Replace keep_dims with keepdims in TF calls; keepdims=True) fetch_dict['x_global_pool'] = net 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') if isFetchDictForDebug: return net, end_points, fetch_dict else: return net, end_points
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): """Generator for v1 ResNet models. 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. 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_v1', [inputs], reuse=reuse) as sc: end_points_collection = sc.original_name_scope + '_end_points' with arg_scope( [layers.conv3d, bottleneck, resnet_3d_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_3d_utils.stack_blocks_dense( net, blocks, output_stride) if global_pool: net = math_ops.reduce_mean(net, [1, 2, 3], name='pool5', keepdims=True) if num_classes is not None: net = layers.conv3d(net, num_classes, [1, 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 and num_classes != 1: end_points['predictions'] = layers_lib.softmax( net, scope='predictions') net = tf.squeeze(net) elif num_classes == 1: net = tf.squeeze(net) end_points['probs'] = tf.nn.sigmoid(net) return net, end_points
def resnet_v2_spkid(self, inputs, spk_labels, blocks, num_classes, is_training, global_pool, output_stride, reuse, scope): with arg_scope(resnet_v2.resnet_arg_scope()): with tf.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, resnet_v2.bottleneck, slim.conv2d, self.stack_blocks_dense ], outputs_collections=end_points_collection): with arg_scope( [layers_lib.conv2d], weights_regularizer=None, weights_initializer=tf.contrib.layers. xavier_initializer(), biases_initializer=tf.constant_initializer(0.001)): with arg_scope( [layers.batch_norm], is_training=is_training, decay=0.9, epsilon=1e-3, scale=True, param_initializers={ "beta": tf.constant_initializer(value=0), "gamma": tf.random_normal_initializer(mean=1, stddev=0.045), "moving_mean": tf.constant_initializer(value=0), "moving_variance": tf.constant_initializer(value=1) }): net = inputs with arg_scope([layers_lib.conv2d], activation_fn=None, normalizer_fn=None, weights_regularizer=None): net = resnet_utils.conv2d_same(net, 64, 13, 1, scope='conv1') # net = layers.max_pool2d(net, [2, 2], stride=2, scope='pool1') # net = resnet_utils.stack_blocks_dense(net, blocks, output_stride) net = self.stack_blocks_dense( net, blocks, output_stride) net = layers.batch_norm(net, activation_fn=tf.nn.relu, scope='postnorm') end_points = utils.convert_collection_to_dict( end_points_collection) net = layers_lib.conv2d(net, 512, [1, 5], stride=1, activation_fn=None, normalizer_fn=None, scope='res_fc', padding='VALID') end_points[sc.name + '/res_fc'] = net net = layers.batch_norm(net, activation_fn=tf.nn.relu, scope='res_fc_bn') if global_pool: ## net : batchsize X W(frame_length) X 1 X Dim ## Global average pooling. # net = tf.reduce_mean(net, [1], name='pool5', keep_dims=True) ## Global statistical pooling # mean,var = tf.nn.moments(net,1,name='pool5', keep_dims=True) # net = tf.concat([mean,var],3) ## Apply attention + stats attention = self.attention_layer(net) end_points['attention'] = attention mean, std = tf.nn.weighted_moments( net, 1, attention, keep_dims=True) net = tf.concat([mean, std], 3) end_points['global_pool'] = net ## Fully Connected layers ## fc1 net = layers_lib.conv2d(net, 1000, [1, 1], stride=1, activation_fn=None, normalizer_fn=None, scope='fc1') end_points[sc.name + '/fc1'] = net net = layers.batch_norm(net, activation_fn=tf.nn.relu, scope='fc1_bn') ## fc2 net = layers_lib.conv2d(net, 512, [1, 1], stride=1, activation_fn=None, normalizer_fn=None, scope='fc2') end_points[sc.name + '/fc2'] = net ## output layer ## For AM-softmax net = tf.squeeze(net, [1, 2], name='SpatialSqueeze') end_points[sc.name + '/spatial_squeeze'] = net net, embedding = self.AM_logits_compute( net, spk_labels, num_classes, is_training) end_points[sc.name + '/logits'] = net end_points[sc.name + '/fc3'] = embedding ## for softmax # net = layers.batch_norm(net, activation_fn=tf.nn.relu, scope='fc2_bn') # net = layers_lib.conv2d(net, num_classes, [1, 1], stride=1, activation_fn=None, # normalizer_fn=None, scope='logits') # end_points[sc.name + '/logits'] = net # net = tf.squeeze(net, [1, 2], name='SpatialSqueeze') # end_points[sc.name + '/spatial_squeeze'] = net ## loss end_points['predictions'] = layers.softmax( net, scope='predictions') loss = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits( labels=spk_labels, logits=net)) end_points[sc.name + '/loss'] = loss end_points[sc.name + '/spk_labels'] = spk_labels return loss, end_points
def Unet(x, labels, keep_prob=1.0, channels=3, n_class=2, num_layers=5, features_root=64, filter_size=3, pool_size=2, summaries=True, trainable=True, reuse=False, scope='dis'): with tf.variable_scope(scope, reuse=reuse): print(scope) end_points = {} logging.info( "Layers {layers}, features {features}, filter size {filter_size}x{filter_size}, pool size: {pool_size}x{pool_size}" .format(layers=layers, features=features_root, filter_size=filter_size, pool_size=pool_size)) # Placeholder for the input image with tf.name_scope("preprocessing"): batch_size = tf.shape(x)[0] nx = tf.shape(x)[1] ny = tf.shape(x)[2] in_node = x weights = [] biases = [] convs = [] pools = OrderedDict() deconv = OrderedDict() dw_h_convs = OrderedDict() up_h_convs = OrderedDict() in_size = 1000 size = in_size # down layers for layer in range(0, num_layers): with tf.variable_scope("down_conv_{}".format(str(layer)), reuse=reuse): features = 2**layer * features_root stddev = np.sqrt(2 / (filter_size**2 * features)) if layer == 0: w1 = weight_variable( [filter_size, filter_size, channels, features], stddev, weight_init, name="w1") else: w1 = weight_variable( [filter_size, filter_size, features // 2, features], stddev, weight_init, name="w1") w2 = weight_variable( [filter_size, filter_size, features, features], stddev, weight_init, name="w2") b1 = bias_variable([features], weight_init, name="b1") b2 = bias_variable([features], weight_init, name="b2") in_node = tf.nn.max_pool(in_node, ksize=[1, 3, 3, 1], strides=[1, 1, 1, 1], padding='SAME') conv1 = conv2d(in_node, w1, b1, keep_prob, reuse=reuse) conv1 = -tf.nn.max_pool(-conv1, ksize=[1, 3, 3, 1], strides=[1, 1, 1, 1], padding='SAME') conv1 = tf_contrib.layers.batch_norm(conv1, decay=0.9, epsilon=1e-05, center=True, scale=True, updates_collections=None, is_training=True) tmp_h_conv = tf.nn.relu(conv1) tmp_h_conv = tf.nn.max_pool(tmp_h_conv, ksize=[1, 3, 3, 1], strides=[1, 1, 1, 1], padding='SAME') conv2 = conv2d(tmp_h_conv, w2, b2, keep_prob, reuse=reuse) conv2 = -tf.nn.max_pool(-conv2, ksize=[1, 3, 3, 1], strides=[1, 1, 1, 1], padding='SAME') conv2 = tf_contrib.layers.batch_norm(conv2, decay=0.9, epsilon=1e-05, center=True, scale=True, updates_collections=None, is_training=True) dw_h_convs[layer] = tf.nn.relu(conv2) print(dw_h_convs[layer]) weights.append((w1, w2)) biases.append((b1, b2)) convs.append((conv1, conv2)) size -= 4 if layer < num_layers - 1: pools[layer] = max_pool(dw_h_convs[layer], pool_size) in_node = pools[layer] size /= 2 in_node = dw_h_convs[num_layers - 1] # up layers for layer in range(num_layers - 2, -1, -1): with tf.variable_scope("up_conv_{}".format(str(layer)), reuse=reuse): features = 2**(layer + 1) * features_root stddev = np.sqrt(2 / (filter_size**2 * features)) wd = weight_variable_devonc( [pool_size, pool_size, features // 2, features], stddev, weight_init, name="wd") bd = bias_variable([features // 2], weight_init, name="bd") h_deconv = tf.nn.relu( deconv2d(in_node, wd, pool_size, reuse=reuse) + bd) h_deconv_concat = tf.concat([dw_h_convs[layer], h_deconv], axis=-1) deconv[layer] = h_deconv_concat w1 = weight_variable( [filter_size, filter_size, features, features // 2], stddev, weight_init, name="w1") w2 = weight_variable( [filter_size, filter_size, features // 2, features // 2], stddev, weight_init, name="w2") b1 = bias_variable([features // 2], weight_init, name="b1") b2 = bias_variable([features // 2], weight_init, name="b2") h_deconv_concat = tf.nn.max_pool(h_deconv_concat, ksize=[1, 3, 3, 1], strides=[1, 1, 1, 1], padding='SAME') conv1 = conv2d(h_deconv_concat, w1, b1, keep_prob, reuse=reuse) conv1 = -tf.nn.max_pool(-conv1, ksize=[1, 3, 3, 1], strides=[1, 1, 1, 1], padding='SAME') conv1 = tf_contrib.layers.batch_norm(conv1, decay=0.9, epsilon=1e-05, center=True, scale=True, updates_collections=None, is_training=True) h_conv = tf.nn.relu(conv1) h_conv = tf.nn.max_pool(h_conv, ksize=[1, 3, 3, 1], strides=[1, 1, 1, 1], padding='SAME') conv2 = conv2d(h_conv, w2, b2, keep_prob, reuse=reuse) conv2 = -tf.nn.max_pool(-conv2, ksize=[1, 3, 3, 1], strides=[1, 1, 1, 1], padding='SAME') conv2 = tf_contrib.layers.batch_norm(conv2, decay=0.9, epsilon=1e-05, center=True, scale=True, updates_collections=None, is_training=True) in_node = tf.nn.relu(conv2) up_h_convs[layer] = in_node print(up_h_convs[layer]) weights.append((w1, w2)) biases.append((b1, b2)) convs.append((conv1, conv2)) size *= 2 size -= 4 # Output Map with tf.name_scope("output_map"): weight = weight_variable([1, 1, features_root, n_class], stddev, weight_init) bias = bias_variable([n_class], weight_init, name="bias") conv = conv2d(in_node, weight, bias, tf.constant(1.0), reuse=reuse) #output_map = tf.nn.relu(conv) output_map = conv up_h_convs["out"] = output_map '''if summaries: with tf.name_scope("summaries"): for i, (c1, c2) in enumerate(convs): tf.summary.image('summary_conv_%02d_01' % i, get_image_summary(c1)) tf.summary.image('summary_conv_%02d_02' % i, get_image_summary(c2)) for k in pools.keys(): tf.summary.image('summary_pool_%02d' % k, get_image_summary(pools[k])) for k in deconv.keys(): tf.summary.image('summary_deconv_concat_%02d' % k, get_image_summary(deconv[k])) ''' '''for k in dw_h_convs.keys(): #tf.summary.histogram("dw_convolution_%02d" % k + '/activations', dw_h_convs[k]) tf.summary.scalar("down_conv_%d" % k + '/gamma1', gamma1) tf.summary.scalar("down_conv_%d" % k + '/gamma2', gamma2) tf.summary.scalar("down_conv_%d" % k + '/gamma3', gamma3) for k in up_h_convs.keys(): #tf.summary.histogram("up_convolution_%s" % k + '/activations', up_h_convs[k]) tf.summary.scalar("up_conv_%d" % k + '/alphabeta1', beta1) tf.summary.scalar("up_conv_%d" % k + '/alphabeta2', beta2) tf.summary.scalar("up_conv_%d" % k + '/alphabeta3', beta3)''' ''' tf.summary.image("out" , get_image_summary(tf.expand_dims(tf.argmax(output_map,-1),-1))) tf.summary.image("label" , get_image_summary(tf.expand_dims(tf.argmax(labels,-1),-1))) tf.summary.image("offset" , get_image_summary(offset1)) tf.summary.image("input" , tf.expand_dims(x[0,:,:,:],0))''' variables = [] for w1, w2 in weights: variables.append(w1) variables.append(w2) for b1, b2 in biases: variables.append(b1) variables.append(b2) end_points['Logits'] = output_map end_points['Predictions'] = layers.softmax(output_map, scope='predictions') end_points['offset'] = layers.softmax(output_map, scope='predictions') return output_map, end_points
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): 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.convolution, 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.convolution], activation_fn=None, normalizer_fn=None): net = conv1d_same(net, 64, 7, stride=2, scope='conv1') net = max_pool1d(net, 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], name='pool5', keep_dims=True) if num_classes is not None: net = layers.convolution(net, num_classes, 1, activation_fn=None, normalizer_fn=None, scope='logits') net = tf.squeeze(net) # 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 resnet_v1(inputs, blocks, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, reuse=None, scope=None): """Generator for v1 ResNet model. This function generates a family of ResNet v1 model. See the resnet_v1_*() 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 0 or None, we return the features before the logit layer. is_training: whether batch_norm layers are in training mode. If this is set to None, the callers can specify slim.batch_norm's is_training parameter from an outer slim.arg_scope. 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. spatial_squeeze: if True, logits is of shape [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. To use this parameter, the input images must be smaller than 300x300 pixels, in which case the output logit layer does not contain spatial information and can be removed. store_non_strided_activations: If True, we compute non-strided (undecimated) activations at the last unit of each block and store them in the `outputs_collections` before subsampling them. This gives us access to higher resolution intermediate activations which are useful in some dense prediction problems but increases 4x the computation and memory cost at the last unit of each block. 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 0 or None, then net is the output of the last ResNet block, potentially after global average pooling. If num_classes a non-zero integer, 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_v1', [inputs], reuse=reuse) as sc: end_points_collection = sc.original_name_scope + '_end_points' with arg_scope( [layers.conv2d, bottleneck, resnet_utils.stack_blocks_dense], outputs_collections=end_points_collection): #with (slim.arg_scope([slim.batch_norm], is_training=is_training) #delete batch_norm #if is_training is not None else NoOpScope()): 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 = resnet_utils.conv2d_same(net, 24, 3, 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) # Convert end_points_collection into a dictionary of end_points. #end_points = slim.utils.convert_collection_to_dict( # end_points_collection) if global_pool: # Global average pooling. net = math_ops.reduce_mean(net, [1, 2], name='pool5', keep_dims=True) #end_points['global_pool'] = net if num_classes is not None: net = layers.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='logits') #end_points[sc.name + '/logits'] = net 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