Example #1
0
 def testVariableCollectionsWithArgScopeNested(self):
     with self.test_session():
         with scopes.arg_scope([variables.variable], collections='A'):
             a = variables.variable('a', [])
             with scopes.arg_scope([variables.variable], collections='B'):
                 b = variables.variable('b', [])
         self.assertEquals(a, tf.get_collection('A')[0])
         self.assertEquals(b, tf.get_collection('B')[0])
Example #2
0
 def testReuseArgScope(self):
     func1_kwargs = {'a': 1, 'b': None, 'c': [1]}
     key_op = (func1.__module__, func1.__name__)
     current_scope = {key_op: func1_kwargs.copy()}
     with self.test_session():
         with scopes.arg_scope([func1], a=1, b=None, c=[1]) as scope1:
             pass
         with scopes.arg_scope(scope1) as scope:
             self.assertDictEqual(scope, current_scope)
Example #3
0
 def testVariableCollectionsWithArgScopeNonNested(self):
     with self.test_session():
         with scopes.arg_scope([variables.variable], collections='A'):
             a = variables.variable('a', [])
         with scopes.arg_scope([variables.variable], collections='B'):
             b = variables.variable('b', [])
         variables.variable('c', [])
         self.assertListEqual([a], tf.get_collection('A'))
         self.assertListEqual([b], tf.get_collection('B'))
Example #4
0
 def testNestedArgScope(self):
     func1_args = (0, )
     func1_kwargs = {'a': 1, 'b': None, 'c': [1]}
     with scopes.arg_scope([func1], a=1, b=None, c=[1]):
         args, kwargs = func1(0)
         self.assertTupleEqual(args, func1_args)
         self.assertDictEqual(kwargs, func1_kwargs)
         func1_kwargs['b'] = 2
         with scopes.arg_scope([func1], b=2):
             args, kwargs = func1(0)
             self.assertTupleEqual(args, func1_args)
             self.assertDictEqual(kwargs, func1_kwargs)
Example #5
0
 def testCurrentArgScopeNested(self):
     func1_kwargs = {'a': 1, 'b': None, 'c': [1]}
     func2_kwargs = {'b': 2, 'd': [2]}
     key = lambda f: (f.__module__, f.__name__)
     current_scope = {
         key(func1): func1_kwargs.copy(),
         key(func2): func2_kwargs.copy()
     }
     with self.test_session():
         with scopes.arg_scope([func1], a=1, b=None, c=[1]):
             with scopes.arg_scope([func2], b=2, d=[2]) as scope:
                 self.assertDictEqual(scope, current_scope)
Example #6
0
 def testPartiallySharedArgScope(self):
     func1_args = (0, )
     func1_kwargs = {'a': 1, 'b': None, 'c': [1]}
     func2_args = (1, )
     func2_kwargs = {'a': 1, 'b': None, 'd': [2]}
     with scopes.arg_scope([func1, func2], a=1, b=None):
         with scopes.arg_scope([func1], c=[1]), scopes.arg_scope([func2],
                                                                 d=[2]):
             args, kwargs = func1(0)
             self.assertTupleEqual(args, func1_args)
             self.assertDictEqual(kwargs, func1_kwargs)
             args, kwargs = func2(1)
             self.assertTupleEqual(args, func2_args)
             self.assertDictEqual(kwargs, func2_kwargs)
Example #7
0
 def testVariableRestoreWithArgScopeNested(self):
     with self.test_session():
         with scopes.arg_scope([variables.variable], restore=True):
             a = variables.variable('a', [])
             with scopes.arg_scope([variables.variable],
                                   trainable=False,
                                   collections=['A', 'B']):
                 b = variables.variable('b', [])
             c = variables.variable('c', [])
         self.assertListEqual([a, b, c],
                              variables.get_variables_to_restore())
         self.assertListEqual([a, c], tf.trainable_variables())
         self.assertListEqual([b], tf.get_collection('A'))
         self.assertListEqual([b], tf.get_collection('B'))
Example #8
0
 def testOverwriteArgScope(self):
     func1_args = (0, )
     func1_kwargs = {'a': 1, 'b': 2, 'c': [1]}
     with scopes.arg_scope([func1], a=1, b=None, c=[1]):
         args, kwargs = func1(0, b=2)
         self.assertTupleEqual(args, func1_args)
         self.assertDictEqual(kwargs, func1_kwargs)
Example #9
0
    def testVariableWithVariableDeviceChooser(self):

        with tf.Graph().as_default():
            device_fn = variables.VariableDeviceChooser(
                num_parameter_servers=2)
            with scopes.arg_scope([variables.variable], device=device_fn):
                a = variables.variable('a', [])
                b = variables.variable('b', [])
                c = variables.variable('c', [], device='cpu:12')
                d = variables.variable('d', [])
                with tf.device('cpu:99'):
                    e_init = tf.constant(12)
                e = variables.variable('e', initializer=e_init)
            # The values below highlight how the VariableDeviceChooser puts initial
            # values on the same device as the variable job.
            self.assertDeviceEqual(a.device, '/job:ps/task:0/cpu:0')
            self.assertDeviceEqual(a.initial_value.device, a.device)
            self.assertDeviceEqual(b.device, '/job:ps/task:1/cpu:0')
            self.assertDeviceEqual(b.initial_value.device, b.device)
            self.assertDeviceEqual(c.device, '/cpu:12')
            self.assertDeviceEqual(c.initial_value.device, c.device)
            self.assertDeviceEqual(d.device, '/job:ps/task:0/cpu:0')
            self.assertDeviceEqual(d.initial_value.device, d.device)
            self.assertDeviceEqual(e.device, '/job:ps/task:1/cpu:0')
            self.assertDeviceEqual(e.initial_value.device, '/cpu:99')
Example #10
0
    def testVariableWithDeviceFunction(self):
        class DevFn(object):
            def __init__(self):
                self.counter = -1

            def __call__(self, op):
                self.counter += 1
                return 'cpu:%d' % self.counter

        with self.test_session():
            with scopes.arg_scope([variables.variable], device=DevFn()):
                a = variables.variable('a', [])
                b = variables.variable('b', [])
                c = variables.variable('c', [], device='cpu:12')
                d = variables.variable('d', [])
                with tf.device('cpu:99'):
                    e_init = tf.constant(12)
                e = variables.variable('e', initializer=e_init)
            self.assertDeviceEqual(a.device, 'cpu:0')
            self.assertDeviceEqual(a.initial_value.device, 'cpu:0')
            self.assertDeviceEqual(b.device, 'cpu:1')
            self.assertDeviceEqual(b.initial_value.device, 'cpu:1')
            self.assertDeviceEqual(c.device, 'cpu:12')
            self.assertDeviceEqual(c.initial_value.device, 'cpu:12')
            self.assertDeviceEqual(d.device, 'cpu:2')
            self.assertDeviceEqual(d.initial_value.device, 'cpu:2')
            self.assertDeviceEqual(e.device, 'cpu:3')
            self.assertDeviceEqual(e.initial_value.device, 'cpu:99')
Example #11
0
 def testSimpleArgScopeWithTuple(self):
     func1_args = (0, )
     func1_kwargs = {'a': 1, 'b': None, 'c': [1]}
     with self.test_session():
         with scopes.arg_scope((func1, ), a=1, b=None, c=[1]):
             args, kwargs = func1(0)
             self.assertTupleEqual(args, func1_args)
             self.assertDictEqual(kwargs, func1_kwargs)
Example #12
0
 def testReuseFCWithBatchNorm(self):
     height, width = 3, 3
     with self.test_session():
         images = tf.random_uniform((5, height * width * 3), seed=1)
         with scopes.arg_scope([ops.fc], batch_norm_params={'decay': 0.9}):
             net = ops.fc(images, 27, scope='fc1')
             net = ops.fc(net, 27, scope='fc1', reuse=True)
         self.assertEquals(len(variables.get_variables()), 4)
         self.assertEquals(len(variables.get_variables('fc1/BatchNorm')), 3)
Example #13
0
 def testSharedArgScopeTuple(self):
     func1_args = (0, )
     func1_kwargs = {'a': 1, 'b': None, 'c': [1]}
     with scopes.arg_scope((func1, func2), a=1, b=None, c=[1]):
         args, kwargs = func1(0)
         self.assertTupleEqual(args, func1_args)
         self.assertDictEqual(kwargs, func1_kwargs)
         args, kwargs = func2(0)
         self.assertTupleEqual(args, func1_args)
         self.assertDictEqual(kwargs, func1_kwargs)
Example #14
0
 def testFCWithBatchNorm(self):
     height, width = 3, 3
     with self.test_session():
         images = tf.random_uniform((5, height * width * 3), seed=1)
         with scopes.arg_scope([ops.fc], batch_norm_params={}):
             net = ops.fc(images, 27)
             net = ops.fc(net, 27)
         self.assertEquals(len(variables.get_variables()), 8)
         self.assertEquals(len(variables.get_variables('FC/BatchNorm')), 3)
         self.assertEquals(len(variables.get_variables('FC_1/BatchNorm')),
                           3)
Example #15
0
    def testVariableWithVariableDeviceChooser(self):

        with tf.Graph().as_default():
            device_fn = variables.VariableDeviceChooser()
            with scopes.arg_scope([variables.global_step], device=device_fn):
                gs = variables.global_step()
                gs2 = variables.global_step()
                self.assertEquals(gs, gs2)
                self.assertDeviceEqual(gs.device, 'cpu:0')
                self.assertDeviceEqual(gs.initial_value.device, gs.device)
                self.assertDeviceEqual(gs2.device, 'cpu:0')
                self.assertDeviceEqual(gs2.initial_value.device, gs2.device)
Example #16
0
 def testReplicaDeviceSetter(self):
     device_fn = tf.train.replica_device_setter(2)
     with tf.Graph().as_default():
         with scopes.arg_scope([variables.global_step], device=device_fn):
             gs = variables.global_step()
             gs2 = variables.global_step()
             self.assertEquals(gs, gs2)
             self.assertDeviceEqual(gs.device, '/job:ps/task:0')
             self.assertDeviceEqual(gs.initial_value.device,
                                    '/job:ps/task:0')
             self.assertDeviceEqual(gs2.device, '/job:ps/task:0')
             self.assertDeviceEqual(gs2.initial_value.device,
                                    '/job:ps/task:0')
Example #17
0
 def testReuseConvWithBatchNorm(self):
     height, width = 3, 3
     with self.test_session():
         images = tf.random_uniform((5, height, width, 32), seed=1)
         with scopes.arg_scope([ops.conv2d],
                               batch_norm_params={'decay': 0.9}):
             net = ops.conv2d(images, 32, [3, 3], scope='Conv')
             net = ops.conv2d(net, 32, [3, 3], scope='Conv', reuse=True)
         self.assertEquals(len(variables.get_variables()), 4)
         self.assertEquals(len(variables.get_variables('Conv/BatchNorm')),
                           3)
         self.assertEquals(len(variables.get_variables('Conv_1/BatchNorm')),
                           0)
Example #18
0
    def testDeviceFn(self):
        class DevFn(object):
            def __init__(self):
                self.counter = -1

            def __call__(self, op):
                self.counter += 1
                return '/cpu:%d' % self.counter

        with tf.Graph().as_default():
            with scopes.arg_scope([variables.global_step], device=DevFn()):
                gs = variables.global_step()
                gs2 = variables.global_step()
            self.assertDeviceEqual(gs.device, '/cpu:0')
            self.assertEquals(gs, gs2)
            self.assertDeviceEqual(gs2.device, '/cpu:0')
Example #19
0
def residual_block(inputs, name='res_block', num_out=None, bn_params=None):
    '''residual convolution block, implementing the following connection:
    in--1-k-1--out
       |__1__| 
    where the numbers denote the kernel size, and k is the conv_kernel
    NOTE: the skip connection is convolved only if num_out is different than num_in
    '''
    conv_kernel = 3
    num_in = inputs.shape[-1].value
    if num_out is None:
        num_out = num_in

    with tf.variable_scope(name):
        with scopes.arg_scope([conv2d], bn_params=bn_params):
            half_num_in = int(num_in // 2)
            out_1 = conv2d(inputs,
                           half_num_in,
                           kernel_size=1,
                           activation=tf.nn.relu,
                           name='conv1_1')
            out_1 = conv2d(out_1,
                           half_num_in,
                           kernel_size=conv_kernel,
                           activation=tf.nn.relu,
                           name='conv1_2')
            out_1 = conv2d(out_1,
                           num_out,
                           kernel_size=1,
                           activation=tf.nn.relu,
                           name='conv1_3')

            if num_out == num_in:
                out_2 = inputs
            else:
                out_2 = conv2d(inputs,
                               num_out,
                               kernel_size=1,
                               activation=tf.nn.relu,
                               name='conv2')

            # add the skip connection
            return out_1 + out_2
Example #20
0
def conv2d(inputs,
           num_filters_out,
           kernel_size,
           stride=1,
           padding='SAME',
           activation=tf.nn.relu,
           stddev=0.01,
           bias=None,
           weight_decay=0,
           batch_norm_params=None,
           is_training=True,
           trainable=True,
           restore=True,
           scope=None):
  """Adds a 2D convolution followed by an optional batch_norm layer.

  conv2d creates a variable called 'weights', representing the convolutional
  kernel, that is convolved with the input. If `batch_norm_params` is None, a
  second variable called 'biases' is added to the result of the convolution
  operation.

  Args:
    inputs: a tensor of size [batch_size, height, width, channels].
    num_filters_out: the number of output filters.
    kernel_size: a 2-D list comprising of the height and width of the filters.
    stride: the stride in height and width of the convolution.
    padding: one of 'VALID' or 'SAME'.
    activation: activation function.
    stddev: standard deviation of the truncated guassian weight distribution.
    bias: the initial value of the biases.
    weight_decay: the weight decay.
    batch_norm_params: parameters for the batch_norm. If is None don't use it.
    is_training: whether or not the model is in training mode.
    trainable: whether or not the variables should be trainable or not.
    restore: whether or not the variables should be marked for restore.
    scope: Optional scope for variable_op_scope.

  Returns:
    a tensor representing the output of the operation.

  Raises:
    ValueError: if 'kernel_size' is not a 2-D list.
  """
  if len(kernel_size) != 2:
    raise ValueError('kernel_size must be a 2-D list.')
  with tf.variable_op_scope([inputs], scope, 'Conv'):
    num_filters_in = inputs.get_shape()[-1]
    #num_filters_in = inputs.get_shape()[-3]
    weights_shape = [kernel_size[0], kernel_size[1],
                     num_filters_in, num_filters_out]
    #weights_initializer = tf.truncated_normal_initializer(stddev=stddev)
    stddev = math.sqrt(2./(kernel_size[0]*kernel_size[1]*num_filters_out))
    weights_initializer = tf.random_normal_initializer(stddev=stddev)
    l2_regularizer = lambda t: losses.l2_loss(t, weight_decay)
    weights = variables.variable('weights',
                                 shape=weights_shape,
                                 initializer=weights_initializer,
                                 regularizer=l2_regularizer,
                                 trainable=trainable,
                                 restore=restore)
    conv = tf.nn.conv2d(inputs, weights, [1, stride, stride, 1],
                        padding=padding)
    #conv = tf.nn.conv2d(inputs, weights, [1, 1, stride, stride],
    #                    padding=padding, data_format='NCHW')
    if batch_norm_params is not None:
      with scopes.arg_scope([batch_norm], is_training=is_training,
                            trainable=trainable, restore=restore):
        outputs = batch_norm(conv, **batch_norm_params)
    elif bias is None:
      outputs = conv
    else:
      bias_shape = [num_filters_out,]
      bias_initializer = tf.constant_initializer(bias)
      biases = variables.variable('biases',
                                  shape=bias_shape,
                                  initializer=bias_initializer,
                                  trainable=trainable,
                                  restore=restore)
      outputs = tf.nn.bias_add(conv, biases)
      #outputs = tf.nn.bias_add(conv, biases, data_format='NCHW')
      #outputs = tf.reshape(outputs, conv.get_shape())
    if activation:
      outputs = activation(outputs)
    return outputs
def conv2d(inputs,
           num_filters_out,
           kernel_size,
           stride=1,
           padding='SAME',
           activation=tf.nn.relu,
           stddev=0.01,
           bias=0.0,
           weight_decay=0,
           batch_norm_params=None,
           is_training=True,
           trainable=True,
           restore=True,
           scope=None,
           reuse=None):
  """Adds a 2D convolution followed by an optional batch_norm layer.

  conv2d creates a variable called 'weights', representing the convolutional
  kernel, that is convolved with the input. If `batch_norm_params` is None, a
  second variable called 'biases' is added to the result of the convolution
  operation.

  Args:
    inputs: a tensor of size [batch_size, height, width, channels].
    num_filters_out: the number of output filters.
    kernel_size: a list of length 2: [kernel_height, kernel_width] of
      of the filters. Can be an int if both values are the same.
    stride: a list of length 2: [stride_height, stride_width].
      Can be an int if both strides are the same.  Note that presently
      both strides must have the same value.
    padding: one of 'VALID' or 'SAME'.
    activation: activation function.
    stddev: standard deviation of the truncated guassian weight distribution.
    bias: the initial value of the biases.
    weight_decay: the weight decay.
    batch_norm_params: parameters for the batch_norm. If is None don't use it.
    is_training: whether or not the model is in training mode.
    trainable: whether or not the variables should be trainable or not.
    restore: whether or not the variables should be marked for restore.
    scope: Optional scope for variable_op_scope.
    reuse: whether or not the layer and its variables should be reused. To be
      able to reuse the layer scope must be given.
  Returns:
    a tensor representing the output of the operation.

  """
  with tf.variable_op_scope([inputs], scope, 'Conv', reuse=reuse):
    kernel_h, kernel_w = _two_element_tuple(kernel_size)
    stride_h, stride_w = _two_element_tuple(stride)
    num_filters_in = inputs.get_shape()[-1]
    weights_shape = [kernel_h, kernel_w,
                     num_filters_in, num_filters_out]
    weights_initializer = tf.truncated_normal_initializer(stddev=stddev)
    l2_regularizer = None
    if weight_decay and weight_decay > 0:
      l2_regularizer = losses.l2_regularizer(weight_decay)
    weights = variables.variable('weights',
                                 shape=weights_shape,
                                 initializer=weights_initializer,
                                 regularizer=l2_regularizer,
                                 trainable=trainable,
                                 restore=restore)
    conv = tf.nn.conv2d(inputs, weights, [1, stride_h, stride_w, 1],
                        padding=padding)
    if batch_norm_params is not None:
      with scopes.arg_scope([batch_norm], is_training=is_training,
                            trainable=trainable, restore=restore):
        outputs = batch_norm(conv, **batch_norm_params)
    else:
      bias_shape = [num_filters_out,]
      bias_initializer = tf.constant_initializer(bias)
      biases = variables.variable('biases',
                                  shape=bias_shape,
                                  initializer=bias_initializer,
                                  trainable=trainable,
                                  restore=restore)
      outputs = tf.nn.bias_add(conv, biases)
    if activation:
      outputs = activation(outputs)
    return outputs
Example #22
0
def fc(inputs,
       num_units_out,
       activation=tf.nn.relu,
       stddev=0.01,
       bias=None,
       weight_decay=0,
       batch_norm_params=None,
       is_training=True,
       trainable=True,
       restore=True,
       scope=None):
    """Adds a fully connected layer followed by an optional batch_norm layer.

  FC creates a variable called 'weights', representing the fully connected
  weight matrix, that is multiplied by the input. If `batch_norm` is None, a
  second variable called 'biases' is added to the result of the initial
  vector-matrix multiplication.

  Args:
    inputs: a [B x N] tensor where B is the batch size and N is the number of
            input units in the layer.
    num_units_out: the number of output units in the layer.
    activation: activation function.
    stddev: the standard deviation for the weights.
    bias: the initial value of the biases.
    weight_decay: the weight decay.
    batch_norm_params: parameters for the batch_norm. If is None don't use it.
    is_training: whether or not the model is in training mode.
    trainable: whether or not the variables should be trainable or not.
    restore: whether or not the variables should be marked for restore.
    scope: Optional scope for variable_op_scope.

  Returns:
     the tensor variable representing the result of the series of operations.
  """
    with tf.variable_op_scope([inputs], scope, 'FC'):
        num_units_in = inputs.get_shape()[1]
        weights_shape = [num_units_in, num_units_out]
        #weights_initializer = tf.truncated_normal_initializer(stddev=stddev)
        weights_initializer = tf.random_normal_initializer(stddev=stddev)
        l2_regularizer = lambda t: losses.l2_loss(t, weight_decay)
        weights = variables.variable('weights',
                                     shape=weights_shape,
                                     initializer=weights_initializer,
                                     regularizer=l2_regularizer,
                                     trainable=trainable,
                                     restore=restore)
        if batch_norm_params is not None:
            outputs = tf.matmul(inputs, weights)
            with scopes.arg_scope([batch_norm],
                                  is_training=is_training,
                                  trainable=trainable,
                                  restore=restore):
                outputs = batch_norm(outputs, **batch_norm_params)
        elif bias is None:
            outputs = tf.matmul(inputs, weights)
        else:
            bias_shape = [
                num_units_out,
            ]
            bias_initializer = tf.constant_initializer(bias)
            biases = variables.variable('biases',
                                        shape=bias_shape,
                                        initializer=bias_initializer,
                                        trainable=trainable,
                                        restore=restore)
            outputs = tf.nn.xw_plus_b(inputs, weights, biases)
        if activation:
            outputs = activation(outputs)
        return outputs
Example #23
0
def conv2d(inputs,
           num_filters_out,
           kernel_size,
           stride=1,
           padding='SAME',
           activation=tf.nn.relu,
           stddev=0.01,
           bias=None,
           weight_decay=0,
           batch_norm_params=None,
           is_training=True,
           trainable=True,
           restore=True,
           scope=None):
    """Adds a 2D convolution followed by an optional batch_norm layer.

  conv2d creates a variable called 'weights', representing the convolutional
  kernel, that is convolved with the input. If `batch_norm_params` is None, a
  second variable called 'biases' is added to the result of the convolution
  operation.

  Args:
    inputs: a tensor of size [batch_size, height, width, channels].
    num_filters_out: the number of output filters.
    kernel_size: a 2-D list comprising of the height and width of the filters.
    stride: the stride in height and width of the convolution.
    padding: one of 'VALID' or 'SAME'.
    activation: activation function.
    stddev: standard deviation of the truncated guassian weight distribution.
    bias: the initial value of the biases.
    weight_decay: the weight decay.
    batch_norm_params: parameters for the batch_norm. If is None don't use it.
    is_training: whether or not the model is in training mode.
    trainable: whether or not the variables should be trainable or not.
    restore: whether or not the variables should be marked for restore.
    scope: Optional scope for variable_op_scope.

  Returns:
    a tensor representing the output of the operation.

  Raises:
    ValueError: if 'kernel_size' is not a 2-D list.
  """
    if len(kernel_size) != 2:
        raise ValueError('kernel_size must be a 2-D list.')
    with tf.variable_op_scope([inputs], scope, 'Conv'):
        num_filters_in = inputs.get_shape()[-1]
        #num_filters_in = inputs.get_shape()[-3]
        weights_shape = [
            kernel_size[0], kernel_size[1], num_filters_in, num_filters_out
        ]
        #weights_initializer = tf.truncated_normal_initializer(stddev=stddev)
        stddev = math.sqrt(2. /
                           (kernel_size[0] * kernel_size[1] * num_filters_out))
        weights_initializer = tf.random_normal_initializer(stddev=stddev)
        l2_regularizer = lambda t: losses.l2_loss(t, weight_decay)
        weights = variables.variable('weights',
                                     shape=weights_shape,
                                     initializer=weights_initializer,
                                     regularizer=l2_regularizer,
                                     trainable=trainable,
                                     restore=restore)
        conv = tf.nn.conv2d(inputs,
                            weights, [1, stride, stride, 1],
                            padding=padding)
        #conv = tf.nn.conv2d(inputs, weights, [1, 1, stride, stride],
        #                    padding=padding, data_format='NCHW')
        if batch_norm_params is not None:
            with scopes.arg_scope([batch_norm],
                                  is_training=is_training,
                                  trainable=trainable,
                                  restore=restore):
                outputs = batch_norm(conv, **batch_norm_params)
        elif bias is None:
            outputs = conv
        else:
            bias_shape = [
                num_filters_out,
            ]
            bias_initializer = tf.constant_initializer(bias)
            biases = variables.variable('biases',
                                        shape=bias_shape,
                                        initializer=bias_initializer,
                                        trainable=trainable,
                                        restore=restore)
            outputs = tf.nn.bias_add(conv, biases)
            #outputs = tf.nn.bias_add(conv, biases, data_format='NCHW')
            #outputs = tf.reshape(outputs, conv.get_shape())
        if activation:
            outputs = activation(outputs)
        return outputs
Example #24
0
 def testDevice(self):
     with tf.Graph().as_default():
         with scopes.arg_scope([variables.global_step], device='/gpu:0'):
             gs = variables.global_step()
         self.assertDeviceEqual(gs.device, '/gpu:0')
Example #25
0
def fc(inputs,
       num_units_out,
       activation=tf.nn.relu,
       stddev=0.01,
       bias=None,
       weight_decay=0,
       batch_norm_params=None,
       is_training=True,
       trainable=True,
       restore=True,
       scope=None):
  """Adds a fully connected layer followed by an optional batch_norm layer.

  FC creates a variable called 'weights', representing the fully connected
  weight matrix, that is multiplied by the input. If `batch_norm` is None, a
  second variable called 'biases' is added to the result of the initial
  vector-matrix multiplication.

  Args:
    inputs: a [B x N] tensor where B is the batch size and N is the number of
            input units in the layer.
    num_units_out: the number of output units in the layer.
    activation: activation function.
    stddev: the standard deviation for the weights.
    bias: the initial value of the biases.
    weight_decay: the weight decay.
    batch_norm_params: parameters for the batch_norm. If is None don't use it.
    is_training: whether or not the model is in training mode.
    trainable: whether or not the variables should be trainable or not.
    restore: whether or not the variables should be marked for restore.
    scope: Optional scope for variable_op_scope.

  Returns:
     the tensor variable representing the result of the series of operations.
  """
  with tf.variable_op_scope([inputs], scope, 'FC'):
    num_units_in = inputs.get_shape()[1]
    weights_shape = [num_units_in, num_units_out]
    #weights_initializer = tf.truncated_normal_initializer(stddev=stddev)
    weights_initializer = tf.random_normal_initializer(stddev=stddev)
    l2_regularizer = lambda t: losses.l2_loss(t, weight_decay)
    weights = variables.variable('weights',
                                 shape=weights_shape,
                                 initializer=weights_initializer,
                                 regularizer=l2_regularizer,
                                 trainable=trainable,
                                 restore=restore)
    if batch_norm_params is not None:
      outputs = tf.matmul(inputs, weights)
      with scopes.arg_scope([batch_norm], is_training=is_training,
                            trainable=trainable, restore=restore):
        outputs = batch_norm(outputs, **batch_norm_params)
    elif bias is None:
      outputs = tf.matmul(inputs, weights)
    else:
      bias_shape = [num_units_out,]
      bias_initializer = tf.constant_initializer(bias)
      biases = variables.variable('biases',
                                  shape=bias_shape,
                                  initializer=bias_initializer,
                                  trainable=trainable,
                                  restore=restore)
      outputs = tf.nn.xw_plus_b(inputs, weights, biases)
    if activation:
      outputs = activation(outputs)
    return outputs
Example #26
0
def batch_norm(inputs,
               decay=0.999,
               scale=False,
               epsilon=0.001,
               moving_vars='moving_vars',
               activation=None,
               is_training=True,
               trainable=True,
               restore=True,
               scope=None):
  """Adds a Batch Normalization layer.

  Args:
    inputs: a tensor of size [batch_size, height, width, channels]
            or [batch_size, channels].
    decay: decay for the moving average.
    scale: If True, multiply by gamma. If False, gamma is
      not used. When the next layer is linear (also e.g. ReLU), this can be
      disabled since the scaling can be done by the next layer.
    epsilon: small float added to variance to avoid dividing by zero.
    moving_vars: collection to store the moving_mean and moving_variance.
    activation: activation function.
    is_training: whether or not the model is in training mode.
    trainable: whether or not the variables should be trainable or not.
    restore: whether or not the variables should be marked for restore.
    scope: Optional scope for variable_op_scope.

  Returns:
    a tensor representing the output of the operation.

  """
  inputs_shape = inputs.get_shape()
  with tf.variable_op_scope([inputs], scope, 'BatchNorm'):
    axis = range(len(inputs_shape) - 1)
    params_shape = inputs_shape[-1:]
    #axis = [0] if len(inputs_shape) == 2 else [0,2,3]
    #params_shape = [tf.Dimension(1),inputs_shape[1]] if len(inputs_shape) == 2 else [tf.Dimension(1),inputs_shape[1],tf.Dimension(1),tf.Dimension(1)]
    with scopes.arg_scope([variables.variable], restore=restore):
      # Allocate parameters for the beta and gamma of the normalization.
      beta = variables.variable('beta',
                                params_shape,
                                initializer=tf.zeros_initializer,
                                trainable=trainable)
      if scale:
        gamma = variables.variable('gamma',
                                   params_shape,
                                   initializer=tf.ones,
                                   trainable=trainable)
      else:
        gamma = None
      # Create moving_mean and moving_variance add them to moving_vars and
      # GraphKeys.MOVING_AVERAGE_VARIABLES collections.
      with scopes.arg_scope([variables.variable], trainable=False,
                            collections=[
                                moving_vars,
                                tf.GraphKeys.MOVING_AVERAGE_VARIABLES]):
        moving_mean = variables.variable('moving_mean',
                                         params_shape,
                                         initializer=tf.zeros_initializer)
        moving_variance = variables.variable('moving_variance',
                                             params_shape,
                                             initializer=tf.ones)
        #moving_mean = tf.Print(moving_mean,[moving_mean],"moving_mean: ")
    if is_training:
      # Calculate the moments based on the individual batch.
      mean, variance = tf.nn.moments(inputs, axis)
      #mean, variance = tf.nn.moments(inputs, axis, keep_dims=True)

      update_moving_mean = moving_averages.assign_moving_average(
          moving_mean, mean, decay)
      tf.add_to_collection(UPDATE_OPS_COLLECTION, update_moving_mean)
      update_moving_variance = moving_averages.assign_moving_average(
          moving_variance, variance, decay)
      tf.add_to_collection(UPDATE_OPS_COLLECTION, update_moving_variance)
    else:
      # Just use the moving_mean and moving_variance.
      mean = moving_mean
      variance = moving_variance
    # Normalize the activations.
    outputs = tf.nn.batch_normalization(
        inputs, mean, variance, beta, gamma, epsilon)
    outputs.set_shape(inputs.get_shape())
    if activation:
      outputs = activation(outputs)
    return outputs
Example #27
0
def conv2d(inputs,
           num_filters_out,
           kernel_size,
           stride=1,
           padding='SAME',
           activation=tf.nn.relu,
           stddev=0.015,
           bias=0.0,
           weight_decay=0,
           batch_norm_params=None,
           is_training=True,
           trainable=True,
           restore=True,
           scope=None,
           reuse=None):
  """Adds a 2D convolution followed by an optional batch_norm layer.

  conv2d creates a variable called 'weights', representing the convolutional
  kernel, that is convolved with the input. If `batch_norm_params` is None, a
  second variable called 'biases' is added to the result of the convolution
  operation.

  Args:
    inputs: a tensor of size [batch_size, height, width, channels].
    num_filters_out: the number of output filters.
    kernel_size: a list of length 2: [kernel_height, kernel_width] of
      of the filters. Can be an int if both values are the same.
    stride: a list of length 2: [stride_height, stride_width].
      Can be an int if both strides are the same.  Note that presently
      both strides must have the same value.
    padding: one of 'VALID' or 'SAME'.
    activation: activation function.
    stddev: standard deviation of the truncated guassian weight distribution.
    bias: the initial value of the biases.
    weight_decay: the weight decay.
    batch_norm_params: parameters for the batch_norm. If is None don't use it.
    is_training: whether or not the model is in training mode.
    trainable: whether or not the variables should be trainable or not.
    restore: whether or not the variables should be marked for restore.
    scope: Optional scope for variable_scope.
    reuse: whether or not the layer and its variables should be reused. To be
      able to reuse the layer scope must be given.
  Returns:
    a tensor representing the output of the operation.

  """
  with tf.variable_scope(scope, 'Conv', [inputs], reuse=reuse):
    kernel_h, kernel_w = _two_element_tuple(kernel_size)
    stride_h, stride_w = _two_element_tuple(stride)
    num_filters_in = inputs.get_shape()[-1]
    weights_shape = [kernel_h, kernel_w,
                     num_filters_in, num_filters_out]
    weights_initializer = tf.truncated_normal_initializer(stddev=stddev)
    l2_regularizer = None
    if weight_decay and weight_decay > 0:
      l2_regularizer = losses.l2_regularizer(weight_decay)
    weights = variables.variable('weights',
                                 shape=weights_shape,
                                 initializer=weights_initializer,
                                 regularizer=l2_regularizer,
                                 trainable=trainable,
                                 restore=restore)
    conv = tf.nn.conv2d(inputs, weights, [1, stride_h, stride_w, 1],
                        padding=padding)
    if batch_norm_params is not None:
      with scopes.arg_scope([batch_norm], is_training=is_training,
                            trainable=trainable, restore=restore):
        outputs = batch_norm(conv, **batch_norm_params)
    else:
      bias_shape = [num_filters_out,]
      bias_initializer = tf.constant_initializer(bias)
      biases = variables.variable('biases',
                                  shape=bias_shape,
                                  initializer=bias_initializer,
                                  trainable=trainable,
                                  restore=restore)
      outputs = tf.nn.bias_add(conv, biases)
    if activation:
      outputs = activation(outputs)
    return outputs