def create_type_discriminator(discrim_inputs): print('type disc:', discrim_inputs.shape) if False: return tf.ones_like(input_types) dim = 32 net = tf.pad(discrim_inputs, [[0, 0], [1, 1], [1, 1], [0, 0]], mode="CONSTANT") net = lrelu(slim.conv2d(net, dim, [4, 4], stride=2)) print(net.shape) net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]], mode="CONSTANT") net = lrelu( tf.nn.dropout( slim.layer_norm(slim.conv2d(net, dim * 2, [4, 4], stride=2)), .5)) print(net.shape) net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]], mode="CONSTANT") net = lrelu( tf.nn.dropout( slim.layer_norm(slim.conv2d(net, dim * 4, [4, 4], stride=2)), .5)) print(net.shape) net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]], mode="CONSTANT") net = lrelu( tf.nn.dropout( slim.layer_norm(slim.conv2d(net, dim * 8, [4, 4], stride=2)), .5)) print(net.shape) #net = tf.pad(net, [[0, 0], [1, 1], [1, 1], [0, 0]], mode="CONSTANT") net = (slim.conv2d(net, number_of_types, [1, 1], stride=1)) #BS, 20, 20, 6 print(net.shape) logits = tf.reduce_mean(net, axis=[1, 2]) return logits
def res_block_ln(inputs, name, kernel_size = 3, strides = 1, padding='same', bias=False): """Residual block with layer normalization""" with tf.variable_scope(name): filters = inputs.get_shape().as_list()[-1] conv1 = tf.nn.relu(slim.layer_norm(conv2d(inputs, filters, 'conv1', kernel_size=kernel_size, strides = strides))) conv2 = slim.layer_norm(conv2d(conv1, filters, 'conv2', kernel_size=kernel_size, strides = strides)) return tf.nn.relu(tf.add(inputs, conv2))
def __call__(self, inputs, state, scope=None): if self._apply_to == 'input': with tf.variable_scope(scope or self._name): inputs = slim.layer_norm(inputs) return self._cell(inputs, state) elif self._apply_to == 'output': output, res_state = self._cell(inputs, state) with tf.variable_scope(scope or self._name): output = slim.layer_norm(output) return output, res_state elif self._apply_to == 'state': output, res_state = self._cell(inputs, state) with tf.variable_scope(scope or self._name): res_state = slim.layer_norm(res_state) return output, res_state else: raise ValueError('Unknown apply_to: "{}"'.format(self._apply_to))
def partial_conv(feature, mask, num_outputs, kernel_size=3, strides=2, ln=True, scope=None): ''' Partial convolutional layer to downsample both feature and mask ''' # apply zero padding to both feature and mask pconv_padding = [[0, 0], [int((kernel_size - 1) / 2), int((kernel_size - 1) / 2)], [int((kernel_size - 1) / 2), int((kernel_size - 1) / 2)], [0, 0]] feature = tf.pad(feature, pconv_padding, "CONSTANT") mask = tf.pad(mask, pconv_padding, "CONSTANT") # apply conv to both feature and mask feature_output = tf.layers.conv2d(inputs=feature * mask, filters=num_outputs, kernel_size=kernel_size, strides=strides, activation=None, use_bias=False, name=scope + '_feature') mask_output = tf.layers.conv2d( inputs=mask, filters=num_outputs, kernel_size=kernel_size, strides=strides, activation=None, kernel_initializer=tf.ones_initializer, use_bias=False, # trainable=False, name=scope + '_mask') # Calculate the mask ratio on each pixel in the output mask window_size = kernel_size * kernel_size * feature.shape._dims[3]._value mask_ratio = tf.divide(window_size, (mask_output + 1e-8)) # Clip output to be between 0 and 1 mask_output = tf.clip_by_value(mask_output, 0, 1) # Remove ratio values where there are holes mask_ratio = mask_ratio * mask_output # Normalize feature output feature_output = feature_output * mask_ratio if ln: feature_output = slim.layer_norm(feature_output, scope=scope + '_ln') feature_output = tf.nn.selu(feature_output) return feature_output, mask_output
def up_sampling(self, x, ch, scope='up_sampling'): with tf.variable_scope(scope): _, h, w, _ = x.get_shape().as_list() new_size = [h * 2, w * 2] up_x = tf.image.resize_nearest_neighbor(x, size=new_size) x = slim.conv2d(up_x, ch, [5, 5], activation_fn=None, scope='conv') x = slim.layer_norm(x, activation_fn=tf.nn.relu) return x
def tower(inputs, is_training, dropout_probability, input_noise, normalize_input, flip_horizontally, translate, growth_rate, total_blocks, depth, bc_mode, reduction, is_initialization=False, name=None): with tf.name_scope(name, "DenseNet"): default_conv_args = dict(padding='SAME', kernel_size=[3, 3], activation_fn=nn.lrelu, init=is_initialization) training_mode_funcs = [ nn.random_translate, nn.flip_randomly, nn.gaussian_noise, slim.dropout, wn.fully_connected, wn.conv2d ] training_args = dict(is_training=is_training) with \ slim.arg_scope([wn.conv2d], **default_conv_args), \ slim.arg_scope(training_mode_funcs, **training_args): #pylint: disable=no-value-for-parameter net = inputs assert_shape(net, [None, 32, 32, 3]) net = tf.cond( normalize_input, lambda: slim.layer_norm( net, scale=False, center=False, scope='normalize_inputs'), lambda: net) assert_shape(net, [None, 32, 32, 3]) net = nn.flip_randomly(net, horizontally=flip_horizontally, vertically=False, name='random_flip') net = tf.cond( translate, lambda: nn.random_translate( net, scale=2, name='random_translate'), lambda: net) net = nn.gaussian_noise(net, scale=input_noise, name='gaussian_noise') DN = DenseNet(growth_rate, total_blocks, depth, bc_mode, reduction, dropout_probability, is_training, 10) primary_logits = DN.build(net) secondary_logits = primary_logits return primary_logits, secondary_logits
def _call(self, inputs, output_size, is_training): inputs = self._subcall(inputs, output_size, is_training) if self._spec.get('ln', False): inputs = slim.layer_norm(inputs) act = self._spec.get('act', False) if act: activation = ACTIVATION_FUNCTIONS[act] return activation(inputs) return inputs
def global_context_module(x, squeeze_depth, fuse_method='add', attention_method='att', scope=None): assert fuse_method in ['add', 'mul'] assert attention_method in ['att', 'avg'] with tf.variable_scope(scope, "GCModule"): if attention_method == 'avg': context = global_avg_pool2D(x) #[N,1,1,C] else: n, h, w, c = x.get_shape().as_list() context_mask = conv(x, 1, 1) # [N, H, W,1] context_mask = tf.reshape(context_mask, shape=tf.convert_to_tensor( [tf.shape(x)[0], -1, 1])) # [N, H*W, 1] context_mask = tf.transpose(context_mask, perm=[0, 2, 1]) # [N, 1, H*W] context_mask = tf.nn.softmax(context_mask, axis=2) # [N, 1, H*W] input_x = tf.reshape(x, shape=tf.convert_to_tensor( [tf.shape(x)[0], -1, c])) # [N,H*W,C] context = tf.matmul(context_mask, input_x) # [N, 1, H*W] x [N,H*W,C] =[N,1,C] context = tf.expand_dims(context, axis=1) #[N,1,1,C] context = conv(context, squeeze_depth, 1) context = slim.layer_norm(context) context = tf.nn.relu(context) context = conv(context, c, 1) #[N,1,1,C] if fuse_method == 'mul': context = tf.nn.sigmoid(context) out = context * x else: out = context + x return out
def deconv_layer(inputs, output_size, input_dim, output_dim, filter_size, stride, padding, normal_type, is_training, name): with tf.variable_scope(name): # 反卷积的kernel的维度是[height, width, output_channel, input_channel] fils = conv_weight_init( [filter_size[0], filter_size[1], output_dim, input_dim], name="weights", stride=stride, mode="Xavier") biases = bias_init([output_dim], name="biases") # weight normalization的实现代码参考了WGAN-GP的源代码 if normal_type == "weight normalization": norm_values = tf.sqrt( tf.reduce_sum(tf.square(fils), axis=[0, 1, 3])) with tf.variable_scope("weight_norm"): norms = tf.sqrt( tf.reduce_sum(tf.square(fils), reduction_indices=[0, 1, 3])) fils = fils * tf.expand_dims(norm_values / norms, 1) deconv = tf.nn.conv2d_transpose(inputs, fils, output_size, strides=stride, padding=padding) result = tf.nn.bias_add(deconv, biases) if normal_type == "layer normalization": result = slim.layer_norm(result, reuse=True, scope="layer_norm") elif normal_type == "instance normalization": result = slim.instance_norm(result, reuse=True, scope="instance_norm") elif normal_type == "batch normalization": result = slim.batch_norm(result, center=True, scale=True, is_training=is_training, scope="batch_norm") elif not normal_type: return result return result
def conv_layer(inputs, input_dim, output_dim, filter_size, strides, padding, normal_type, is_training, name): with tf.variable_scope(name): fils = conv_weight_init( [filter_size[0], filter_size[1], input_dim, output_dim], name="weights", stride=strides, mode="Xavier") biases = bias_init([output_dim], name="biases") # weight normalization作用于模型参数权值,因此是加在卷积计算前面 # weight normalization的实现代码参考了WGAN-GP的源代码 if normal_type == "weight normalization": norm_values = tf.sqrt( tf.reduce_sum(tf.square(fils), axis=[0, 1, 2])) with tf.variable_scope("weight_norm"): norms = tf.sqrt( tf.reduce_sum(tf.square(fils), reduction_indices=[0, 1, 2])) fils = fils * (norm_values / norms) conv = tf.nn.conv2d(inputs, fils, strides, padding=padding) result = tf.nn.bias_add(conv, biases) # 在WGAN-GP论文中指出不要用batch normalization # 可以用其他normalization方法如layer normalization、weight normalization、instance normalization代替 # 论文中推荐使用layer normalization if normal_type == "layer normalization": result = slim.layer_norm(result, reuse=True, scope="layer_norm") elif normal_type == "instance normalization": result = slim.instance_norm(result, reuse=True, scope="instance_norm") elif normal_type == "batch normalization": result = slim.batch_norm(result, center=True, scale=True, is_training=is_training, scope="batch_norm") elif not normal_type: return result return result
def _normalization(self, tensor_in, training=True): if cfg.MODEL.NORMALIZATION == "batch_norm": # batch_norm need UPDATE_OPS tensor_out = slim.batch_norm(tensor_in, scale=True, is_training=training, activation_fn=self._activation()) elif cfg.MODEL.NORMALIZATION == "instance_norm": tensor_out = slim.instance_norm(tensor_in, trainable=training, activation_fn=self._activation()) elif cfg.MODEL.NORMALIZATION == "layer_norm": tensor_out = slim.layer_norm(tensor_in, trainable=training, activation_fn=self._activation()) else: raise ValueError("Unsuppoerted normalization function: %s" % cfg.MODEL.NORMALIZATION) return tensor_out
def solar24(inputs, is_training, dropout_probability, input_noise, normalize_input, flip_horizontally, translate, is_initialization=False, training = False, name=None): with tf.name_scope(name, "solar24"): training_mode_funcs = [ nn.step_noise_solar, nn.step_noise_solar24,slim.dropout, wn.fully_connected,nn.gaussian_noise ] training_args = dict( is_training=is_training ) with slim.arg_scope(training_mode_funcs, **training_args): net = inputs assert_shape(net, [None, 24]) # net = nn.gaussian_noise(net, scale=input_noise['gaussian'], name='gaussian_noise') net = nn.step_noise_solar24(net, step_size=input_noise, name='step_noise') net = tf.cond(tf.convert_to_tensor(normalize_input), lambda: slim.layer_norm(net, scale=False, center=False, scope='normalize_inputs'), lambda: net) net = wn.fully_connected(net, 16, init=is_initialization,activation_fn=nn.lrelu,scope="dense_1") net = wn.fully_connected(net, 32, init=is_initialization,activation_fn=nn.lrelu,scope="dense_2") net = slim.dropout(net, 1 - dropout_probability, scope='dropout') primary_logits = wn.fully_connected(net, 1, init=is_initialization,scope="dense_out") return primary_logits
def Transform_layer(self, att_input, module_idx, dim_lambda, att_unit, num_heads, mode=[1, 1], mask=None, flat_attention=False): net = slim.conv2d(att_input, dim_lambda, 3, stride=1, padding='SAME', activation_fn=None, scope='Chan_Dim_%d' % (module_idx)) net_CDSA = self.CDSA_Module(net, module_idx, dim_lambda, att_unit, num_heads, mode, mask, flat_attention) net = slim.layer_norm(net_CDSA + net, scope='CDSA_Norm_%d' % (module_idx)) #print('CDSA', module_idx, net_CDSA.get_shape().as_list()) return net
def create_discriminator(discrim_inputs): print('quality disc:', discrim_inputs.shape) if False: return tf.reduce_mean(discrim_inputs) n_layers = 3 layers = [] # 2x [batch, height, width, in_channels] => [batch, height, width, in_channels * 2] # input = tf.concat([discrim_inputs, discrim_targets], axis=3) input = discrim_inputs # layer_1: [batch, 256, 256, in_channels * 2] => [batch, 128, 128, ndf] with tf.variable_scope("layer_1"): convolved = discrim_conv(input, a.ndf, stride=2) rectified = lrelu(convolved, 0.2) layers.append(rectified) # layer_2: [batch, 128, 128, ndf] => [batch, 64, 64, ndf * 2] # layer_3: [batch, 64, 64, ndf * 2] => [batch, 32, 32, ndf * 4] # layer_4: [batch, 32, 32, ndf * 4] => [batch, 31, 31, ndf * 8] for i in range(n_layers): with tf.variable_scope("layer_%d" % (len(layers) + 1)): out_channels = a.ndf * min(2**(i + 1), 8) stride = 1 if i == n_layers - 1 else 2 # last layer here has stride 1 convolved = discrim_conv(layers[-1], out_channels, stride=stride) # normalized = batchnorm(convolved) normalized = slim.layer_norm(convolved) rectified = lrelu(normalized, 0.2) print(rectified.shape) layers.append(rectified) # layer_5: [batch, 31, 31, ndf * 8] => [batch, 30, 30, 1] with tf.variable_scope("layer_%d" % (len(layers) + 1)): convolved = discrim_conv(rectified, out_channels=1, stride=1) output = tf.sigmoid(convolved) layers.append(output) return layers[-1]
def Layer_Normalization(x, scope): return slim.layer_norm(x, scope=scope)
def tower(inputs, is_training, normalize_input, flip_horizontally, is_initialization=False, name=None): with tf.name_scope(name, "tower"): default_conv_args = dict(padding='SAME', kernel_size=[3, 3], activation_fn=nn.lrelu, init=is_initialization) training_mode_funcs = [ nn.random_translate, nn.flip_randomly, nn.gaussian_noise, slim.dropout, wn.fully_connected, wn.conv2d ] training_args = dict(is_training=is_training) with \ slim.arg_scope([wn.conv2d], **default_conv_args), \ slim.arg_scope(training_mode_funcs, **training_args): #pylint: disable=no-value-for-parameter net = inputs assert_shape(net, [None, 32, 32, 3]) net = tf.cond( normalize_input, lambda: slim.layer_norm( net, scale=False, center=False, scope='normalize_inputs'), lambda: net) assert_shape(net, [None, 32, 32, 3]) net = nn.flip_randomly(net, horizontally=flip_horizontally, vertically=False, name='random_flip') net = nn.random_translate(net, scale=2, name='random_translate') net = nn.gaussian_noise(net, scale=0.15, name='gaussian_noise') net = wn.conv2d(net, 128, scope="conv_1_1") net = wn.conv2d(net, 128, scope="conv_1_2") net = wn.conv2d(net, 128, scope="conv_1_3") net = slim.max_pool2d(net, [2, 2], scope='max_pool_1') net = slim.dropout(net, 0.5, scope='dropout_1') assert_shape(net, [None, 16, 16, 128]) net = wn.conv2d(net, 256, scope="conv_2_1") net = wn.conv2d(net, 256, scope="conv_2_2") net = wn.conv2d(net, 256, scope="conv_2_3") net = slim.max_pool2d(net, [2, 2], scope='max_pool_2') net = slim.dropout(net, 0.5, scope='dropout_2') assert_shape(net, [None, 8, 8, 256]) net = wn.conv2d(net, 512, padding='VALID', scope="conv_3_1") assert_shape(net, [None, 6, 6, 512]) net = wn.conv2d(net, 256, kernel_size=[1, 1], scope="conv_3_2") net = wn.conv2d(net, 128, kernel_size=[1, 1], scope="conv_3_3") net = slim.avg_pool2d(net, [6, 6], scope='avg_pool') assert_shape(net, [None, 1, 1, 128]) net = slim.flatten(net) assert_shape(net, [None, 128]) net = wn.fully_connected(net, 10, init=is_initialization, scope="fully_connected") assert_shape(net, [None, 10]) return net
def resnet_v2(inputs, blocks, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, spatial_squeeze=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 0 or None, we return the features before the logit layer. is_training: whether layer_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. 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. 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 is 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 tf.variable_scope(scope, 'resnet_v2', [inputs], reuse=reuse) as sc: end_points_collection = sc.original_name_scope + '_end_points' with slim.arg_scope( [slim.conv2d, bottleneck, resnet_utils.stack_blocks_dense], outputs_collections=end_points_collection): 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 slim.arg_scope([slim.conv2d], activation_fn=None, normalizer_fn=None): net = resnet_utils.conv2d_same(net, 64, 7, stride=2, scope='conv1') net = slim.max_pool2d(net, [3, 3], stride=2, scope='pool1') net = resnet_utils.stack_blocks_dense(net, blocks, output_stride) # 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.layer_norm(net, activation_fn=tf.nn.relu, scope='postnorm') # 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 = tf.reduce_mean(net, [1, 2], name='pool5', keep_dims=True) end_points['global_pool'] = net if num_classes is not None: net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='logits') end_points[sc.name + '/logits'] = net if spatial_squeeze: net = tf.squeeze(net, [1, 2], name='SpatialSqueeze') end_points[sc.name + '/spatial_squeeze'] = net end_points['Logits'] = net end_points['Predictions'] = slim.softmax(net, scope='predictions') return net, end_points
def create_generator(generator_inputs): print('gen:', generator_inputs.shape) if False: return tf.stack([generator_inputs for x in range(6)], axis=1) layers = [] # encoder_1: [batch, 256, 256, in_channels] => [batch, 128, 128, ngf] with tf.variable_scope("encoder_1"): output = gen_conv(generator_inputs, a.ngf) layers.append(output) layer_specs = [ a.ngf * 2, # encoder_2: [batch, 128, 128, ngf] => [batch, 64, 64, ngf * 2] a.ngf * 4, # encoder_3: [batch, 64, 64, ngf * 2] => [batch, 32, 32, ngf * 4] a.ngf * 8, # encoder_4: [batch, 32, 32, ngf * 4] => [batch, 16, 16, ngf * 8] a.ngf * 8, # encoder_5: [batch, 16, 16, ngf * 8] => [batch, 8, 8, ngf * 8] a.ngf * 8, # encoder_6: [batch, 8, 8, ngf * 8] => [batch, 4, 4, ngf * 8] a.ngf * 8, # encoder_7: [batch, 4, 4, ngf * 8] => [batch, 2, 2, ngf * 8] a.ngf * 8, # encoder_8: [batch, 2, 2, ngf * 8] => [batch, 1, 1, ngf * 8] ] for out_channels in layer_specs: with tf.variable_scope("encoder_%d" % (len(layers) + 1)): rectified = lrelu(layers[-1], 0.2) # [batch, in_height, in_width, in_channels] => [batch, in_height/2, in_width/2, out_channels] convolved = gen_conv(rectified, out_channels) # output = slim.layer_norm(convolved) output = instance_norm(convolved) layers.append(output) layer_specs = [ (a.ngf * 8, 0.5 ), # decoder_8: [batch, 1, 1, ngf * 8] => [batch, 2, 2, ngf * 8 * 2] ( a.ngf * 8, 0.5 ), # decoder_7: [batch, 2, 2, ngf * 8 * 2] => [batch, 4, 4, ngf * 8 * 2] ( a.ngf * 8, 0.5 ), # decoder_6: [batch, 4, 4, ngf * 8 * 2] => [batch, 8, 8, ngf * 8 * 2] ( a.ngf * 8, 0.0 ), # decoder_5: [batch, 8, 8, ngf * 8 * 2] => [batch, 16, 16, ngf * 8 * 2] ( a.ngf * 4, 0.0 ), # decoder_4: [batch, 16, 16, ngf * 8 * 2] => [batch, 32, 32, ngf * 4 * 2] ( a.ngf * 2, 0.0 ), # decoder_3: [batch, 32, 32, ngf * 4 * 2] => [batch, 64, 64, ngf * 2 * 2] ( a.ngf, 0.0 ), # decoder_2: [batch, 64, 64, ngf * 2 * 2] => [batch, 128, 128, ngf * 2] ] num_encoder_layers = len(layers) for decoder_layer, (out_channels, dropout) in enumerate(layer_specs): skip_layer = num_encoder_layers - decoder_layer - 1 with tf.variable_scope("decoder_%d" % (skip_layer + 1)): if decoder_layer == 0: # first decoder layer doesn't have skip connections # since it is directly connected to the skip_layer input = layers[-1] else: input = tf.concat([layers[-1], layers[skip_layer]], axis=3) rectified = lrelu(input) # [batch, in_height, in_width, in_channels] => [batch, in_height*2, in_width*2, out_channels] output = gen_deconv(rectified, out_channels) output = slim.layer_norm(output) '''remove this during testing?''' if dropout > 0.0: # if a.mode=='train': if True: print("using dropout") output = tf.nn.dropout(output, keep_prob=1 - dropout) layers.append(output) generator_outputs_channels = 3 * number_of_types # decoder_1: [batch, 128, 128, ngf * 2] => [batch, 256, 256, generator_outputs_channels] with tf.variable_scope("decoder_1"): input = tf.concat([layers[-1], layers[0]], axis=3) rectified = lrelu(input) output = gen_deconv(rectified, generator_outputs_channels) output = tf.tanh(output) layers.append(output) print(layers[-1].shape) output = tf.reshape(layers[-1], [-1, number_of_types, 256, 256, 3]) return 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 tf.variable_scope(scope, 'bottleneck_v2', [inputs]) as sc: depth_in = slim.utils.last_dimension(inputs.get_shape(), min_rank=4) preact = slim.layer_norm(inputs, activation_fn=tf.nn.relu, scope='preact') if depth == depth_in: shortcut = resnet_utils.subsample(inputs, stride, 'shortcut') else: shortcut = slim.conv2d(preact, depth, [1, 1], stride=stride, normalizer_fn=None, activation_fn=None, scope='shortcut') residual = slim.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 = slim.conv2d(residual, depth, [1, 1], stride=1, normalizer_fn=None, activation_fn=None, scope='conv3') output = shortcut + residual return slim.utils.collect_named_outputs(outputs_collections, sc.name, output)
def har_conv2d(inputs, is_training, dropout_probability, input_noise, normalize_input, flip_horizontally, translate, is_initialization=False, name=None, bg_noise=False, bg_noise_level=0, bg_noise_input=None, resize = False): with tf.name_scope(name, "tower"): default_conv_args = dict( padding='SAME', kernel_size=[3, 3], activation_fn=nn.lrelu, init=is_initialization ) training_mode_funcs = [ nn.random_translate, nn.flip_randomly, nn.gaussian_noise, slim.dropout, wn.fully_connected, wn.conv2d, nn.resize ] training_args = dict( is_training=is_training ) with \ slim.arg_scope([wn.conv2d], **default_conv_args), \ slim.arg_scope(training_mode_funcs, **training_args): net = inputs assert_shape(net, [None, 9, 64, 1]) net = tf.cond(tf.convert_to_tensor(normalize_input), lambda: slim.layer_norm(net, scale=False, center=False, scope='normalize_inputs'), lambda: net) # net = tf.cond(tf.convert_to_tensor(translate), # lambda: nn.random_translate(net, scale=[0,2], name='random_translate'), # lambda: net) # net = tf.cond(tf.convert_to_tensor(resize), # lambda: nn.resize(net,scale=1, name='resize_aug'), # lambda: net) net = nn.gaussian_noise(net, scale=input_noise, name='gaussian_noise') net = wn.conv2d(net, 128, scope="conv_1_1") net = wn.conv2d(net, 128, scope="conv_1_2") # net = wn.conv2d(net, 128, scope="conv_1_3") net = slim.max_pool2d(net, [1, 2],stride=[1,2], scope='max_pool_1') net = slim.dropout(net, 1 - dropout_probability, scope='dropout_probability_1') assert_shape(net, [None, 9, 32, 128]) net = wn.conv2d(net, 256, scope="conv_2_1") net = wn.conv2d(net, 256, scope="conv_2_2") # net = wn.conv2d(net, 256, scope="conv_2_3") net = slim.max_pool2d(net, [1, 2], stride=[1,2],scope='max_pool_2') net = slim.dropout(net, 1 - dropout_probability, scope='dropout_probability_2') assert_shape(net, [None, 9, 16, 256]) net = wn.conv2d(net, 256, scope="conv_3_1") net = wn.conv2d(net, 256, scope="conv_3_2") # net = wn.conv2d(net, 256, scope="conv_2_3") net = slim.max_pool2d(net, [1, 2],stride=[1,2], scope='max_pool_3') net = slim.dropout(net, 1 - dropout_probability, scope='dropout_probability_2') assert_shape(net, [None, 9, 8, 256]) net = wn.conv2d(net, 512, padding='VALID', scope="conv_4_1") assert_shape(net, [None, 7, 6, 512]) net = wn.conv2d(net, 256, kernel_size=[1, 1], scope="conv_4_2") net = wn.conv2d(net, 128, kernel_size=[1, 1], scope="conv_4_3") net = slim.avg_pool2d(net, [7, 6], scope='avg_pool') assert_shape(net, [None, 1, 1, 128]) net = slim.flatten(net) assert_shape(net, [None, 128]) primary_logits = wn.fully_connected(net, 24, init=is_initialization) assert_shape(primary_logits, [None, 24]) return primary_logits
def audio(inputs, is_training, dropout_probability, input_noise, normalize_input, flip_horizontally, translate, is_initialization=False, name=None, bg_noise=False, bg_noise_level=0, bg_noise_input=None): with tf.name_scope(name, "audio"): default_conv_args = dict(padding='SAME', kernel_size=[3, 3], activation_fn=nn.lrelu, init=is_initialization) training_mode_funcs = [ nn.random_translate, nn.flip_randomly, nn.gaussian_noise, slim.dropout, nn.bg_noise_layer, wn.fully_connected, wn.conv2d ] training_args = dict(is_training=is_training) with \ slim.arg_scope([wn.conv2d], **default_conv_args), \ slim.arg_scope(training_mode_funcs, **training_args): #pylint: disable=no-value-for-parameter net = inputs net = tf.cond( tf.convert_to_tensor(bg_noise), lambda: nn.bg_noise_layer(net, bg_noise_level=bg_noise_level, bg_noise_input=bg_noise_input), lambda: net) net = tf.cond( tf.convert_to_tensor(normalize_input), lambda: slim.layer_norm( net, scale=False, center=False, scope='normalize_inputs'), lambda: net) net = nn.flip_randomly(net, horizontally=flip_horizontally, vertically=False, name='random_flip') net = tf.cond( tf.convert_to_tensor(translate), lambda: nn.random_translate( net, scale=2, name='random_translate'), lambda: net) net = nn.gaussian_noise(net, scale=input_noise, name='gaussian_noise') net = wn.conv2d(net, 128, scope="conv_1_1") net = wn.conv2d(net, 128, scope="conv_1_2") net = wn.conv2d(net, 128, scope="conv_1_3") net = slim.max_pool2d(net, [2, 2], scope='max_pool_1') net = slim.dropout(net, 1 - dropout_probability, scope='dropout_probability_1') net = wn.conv2d(net, 256, scope="conv_2_1") net = wn.conv2d(net, 256, scope="conv_2_2") net = wn.conv2d(net, 256, scope="conv_2_3") net = slim.max_pool2d(net, [2, 2], scope='max_pool_2') net = slim.dropout(net, 1 - dropout_probability, scope='dropout_probability_2') net = wn.conv2d(net, 512, padding='VALID', scope="conv_3_1") net = wn.conv2d(net, 256, kernel_size=[1, 1], scope="conv_3_2") net = wn.conv2d(net, 128, kernel_size=[1, 1], scope="conv_3_3") net = slim.avg_pool2d(net, [6, 6], scope='avg_pool') net = slim.flatten(net) primary_logits = wn.fully_connected(net, 30, init=is_initialization) return primary_logits
def layer_norm(x, scope): with tf.variable_scope(scope): return slim.layer_norm(x, activation_fn=None)
def tower(inputs, is_training, dropout_probability, input_noise, normalize_input, flip_horizontally, translate, num_logits, is_initialization=False, name=None): with tf.name_scope(name, "tower"): default_conv_args = dict(padding='SAME', kernel_size=[3, 3], activation_fn=nn.lrelu, init=is_initialization) training_mode_funcs = [ nn.random_translate, nn.flip_randomly, nn.gaussian_noise, slim.dropout, wn.fully_connected, wn.conv2d ] training_args = dict(is_training=is_training) with \ slim.arg_scope([wn.conv2d], **default_conv_args), \ slim.arg_scope(training_mode_funcs, **training_args): #pylint: disable=no-value-for-parameter net = inputs assert_shape(net, [None, 32, 32, 3]) net = tf.cond( normalize_input, lambda: slim.layer_norm( net, scale=False, center=False, scope='normalize_inputs'), lambda: net) assert_shape(net, [None, 32, 32, 3]) net = nn.flip_randomly(net, horizontally=flip_horizontally, vertically=False, name='random_flip') net = tf.cond( translate, lambda: nn.random_translate( net, scale=2, name='random_translate'), lambda: net) net = nn.gaussian_noise(net, scale=input_noise, name='gaussian_noise') net = wn.conv2d(net, 128, scope="conv_1_1") net = wn.conv2d(net, 128, scope="conv_1_2") net = wn.conv2d(net, 128, scope="conv_1_3") net = slim.max_pool2d(net, [2, 2], scope='max_pool_1') net = slim.dropout(net, 1 - dropout_probability, scope='dropout_probability_1') assert_shape(net, [None, 16, 16, 128]) net = wn.conv2d(net, 256, scope="conv_2_1") net = wn.conv2d(net, 256, scope="conv_2_2") net = wn.conv2d(net, 256, scope="conv_2_3") net = slim.max_pool2d(net, [2, 2], scope='max_pool_2') net = slim.dropout(net, 1 - dropout_probability, scope='dropout_probability_2') assert_shape(net, [None, 8, 8, 256]) net = wn.conv2d(net, 512, padding='VALID', scope="conv_3_1") assert_shape(net, [None, 6, 6, 512]) net = wn.conv2d(net, 256, kernel_size=[1, 1], scope="conv_3_2") net = wn.conv2d(net, 128, kernel_size=[1, 1], scope="conv_3_3") net = slim.avg_pool2d(net, [6, 6], scope='avg_pool') assert_shape(net, [None, 1, 1, 128]) net = slim.flatten(net) assert_shape(net, [None, 128]) primary_logits = wn.fully_connected(net, 10, init=is_initialization) secondary_logits = wn.fully_connected(net, 10, init=is_initialization) with tf.control_dependencies([ tf.assert_greater_equal(num_logits, 1), tf.assert_less_equal(num_logits, 2) ]): secondary_logits = tf.case([ (tf.equal(num_logits, 1), lambda: primary_logits), (tf.equal(num_logits, 2), lambda: secondary_logits), ], exclusive=True, default=lambda: primary_logits) assert_shape(primary_logits, [None, 10]) assert_shape(secondary_logits, [None, 10]) return primary_logits, secondary_logits
def tower(inputs, is_training, dropout_probability, input_noise, normalize_input, flip_horizontally, translate, num_logits, is_initialization=False, name=None): with tf.name_scope(name, "tower"): default_conv_args = dict( padding='SAME', kernel_size=[3, 3], activation_fn=nn.lrelu, init=is_initialization ) training_mode_funcs = [ nn.random_translate, nn.flip_randomly, nn.gaussian_noise, slim.dropout, wn.fully_connected, wn.conv2d ] training_args = dict( is_training=is_training ) with \ slim.arg_scope([wn.conv2d], **default_conv_args), \ slim.arg_scope(training_mode_funcs, **training_args): #pylint: disable=no-value-for-parameter net = inputs assert_shape(net, [None, 32, 32, 3]) net = tf.cond(normalize_input, lambda: slim.layer_norm(net, scale=False, center=False, scope='normalize_inputs'), lambda: net) assert_shape(net, [None, 32, 32, 3]) net = nn.flip_randomly(net, horizontally=flip_horizontally, vertically=False, name='random_flip') net = tf.cond(translate, lambda: nn.random_translate(net, scale=2, name='random_translate'), lambda: net) net = nn.gaussian_noise(net, scale=input_noise, name='gaussian_noise') net = wn.conv2d(net, 128, scope="conv_1_1") net = wn.conv2d(net, 128, scope="conv_1_2") net = wn.conv2d(net, 128, scope="conv_1_3") net = slim.max_pool2d(net, [2, 2], scope='max_pool_1') net = slim.dropout(net, 1 - dropout_probability, scope='dropout_probability_1') assert_shape(net, [None, 16, 16, 128]) net = wn.conv2d(net, 256, scope="conv_2_1") net = wn.conv2d(net, 256, scope="conv_2_2") net = wn.conv2d(net, 256, scope="conv_2_3") net = slim.max_pool2d(net, [2, 2], scope='max_pool_2') net = slim.dropout(net, 1 - dropout_probability, scope='dropout_probability_2') assert_shape(net, [None, 8, 8, 256]) net = wn.conv2d(net, 512, padding='VALID', scope="conv_3_1") assert_shape(net, [None, 6, 6, 512]) net = wn.conv2d(net, 256, kernel_size=[1, 1], scope="conv_3_2") net = wn.conv2d(net, 128, kernel_size=[1, 1], scope="conv_3_3") net = slim.avg_pool2d(net, [6, 6], scope='avg_pool') assert_shape(net, [None, 1, 1, 128]) net = slim.flatten(net) assert_shape(net, [None, 128]) primary_logits = wn.fully_connected(net, 10, init=is_initialization) secondary_logits = wn.fully_connected(net, 10, init=is_initialization) with tf.control_dependencies([tf.assert_greater_equal(num_logits, 1), tf.assert_less_equal(num_logits, 2)]): secondary_logits = tf.case([ (tf.equal(num_logits, 1), lambda: primary_logits), (tf.equal(num_logits, 2), lambda: secondary_logits), ], exclusive=True, default=lambda: primary_logits) assert_shape(primary_logits, [None, 10]) assert_shape(secondary_logits, [None, 10]) return primary_logits, secondary_logits