def block17(net, scale=1.0, activation="relu"): tower_conv = relu( batch_normalization( conv_2d(net, 192, 1, bias=False, activation=None, name='Conv2d_1x1'))) tower_conv_1_0 = relu( batch_normalization( conv_2d(net, 128, 1, bias=False, activation=None, name='Conv2d_0a_1x1'))) tower_conv_1_1 = relu( batch_normalization( conv_2d(tower_conv_1_0, 160, [1, 7], bias=False, activation=None, name='Conv2d_0b_1x7'))) tower_conv_1_2 = relu( batch_normalization( conv_2d(tower_conv_1_1, 192, [7, 1], bias=False, activation=None, name='Conv2d_0c_7x1'))) tower_mixed = merge([tower_conv, tower_conv_1_2], mode='concat', axis=3) tower_out = relu( batch_normalization( conv_2d(tower_mixed, net.get_shape()[3], 1, bias=False, activation=None, name='Conv2d_1x1'))) net += scale * tower_out if activation: if isinstance(activation, str): net = activations.get(activation)(net) elif hasattr(activation, '__call__'): net = activation(net) else: raise ValueError("Invalid Activation.") return net
def activation(incoming, activation='linear', name='activation'): """ Activation. Apply given activation to incoming tensor. Arguments: incoming: A `Tensor`. The incoming tensor. activation: `str` (name) or `function` (returning a `Tensor`). Activation applied to this layer (see tflearn.activations). Default: 'linear'. """ if isinstance(activation, str): x = activations.get(activation)(incoming) elif hasattr(activation, '__call__'): x = activation(incoming) else: raise ValueError('Unknown activation type.') # Track output tensor. tf.add_to_collection(tf.GraphKeys.LAYER_TENSOR + '/' + name, x) return x
def highway(incoming, n_units, activation='linear', transform_dropout=None, weights_init='truncated_normal', bias_init='zeros', regularizer=None, weight_decay=0.001, trainable=True, restore=True, reuse=False, scope=None, name="FullyConnectedHighway"): """ Fully Connected Highway. A fully connected highway network layer, with some inspiration from [https://github.com/fomorians/highway-fcn](https://github.com/fomorians/highway-fcn). Input: (2+)-D Tensor [samples, input dim]. If not 2D, input will be flatten. Output: 2D Tensor [samples, n_units]. Arguments: incoming: `Tensor`. Incoming (2+)D Tensor. n_units: `int`, number of units for this layer. activation: `str` (name) or `function` (returning a `Tensor`). Activation applied to this layer (see tflearn.activations). Default: 'linear'. transform_dropout: `float`: Keep probability on the highway transform gate. weights_init: `str` (name) or `Tensor`. Weights initialization. (see tflearn.initializations) Default: 'truncated_normal'. bias_init: `str` (name) or `Tensor`. Bias initialization. (see tflearn.initializations) Default: 'zeros'. regularizer: `str` (name) or `Tensor`. Add a regularizer to this layer weights (see tflearn.regularizers). Default: None. weight_decay: `float`. Regularizer decay parameter. Default: 0.001. trainable: `bool`. If True, weights will be trainable. restore: `bool`. If True, this layer weights will be restored when loading a model reuse: `bool`. If True and 'scope' is provided, this layer variables will be reused (shared). scope: `str`. Define this layer scope (optional). A scope can be used to share variables between layers. Note that scope will override name. name: A name for this layer (optional). Default: 'FullyConnectedHighway'. Attributes: scope: `Scope`. This layer scope. W: `Tensor`. Variable representing units weights. W_t: `Tensor`. Variable representing units weights for transform gate. b: `Tensor`. Variable representing biases. b_t: `Tensor`. Variable representing biases for transform gate. Links: [https://arxiv.org/abs/1505.00387](https://arxiv.org/abs/1505.00387) """ input_shape = utils.get_incoming_shape(incoming) assert len(input_shape) > 1, "Incoming Tensor shape must be at least 2-D" n_inputs = int(np.prod(input_shape[1:])) # Build variables and inference. with tf.variable_scope(scope, default_name=name, values=[incoming], reuse=reuse) as scope: name = scope.name W_init = weights_init if isinstance(weights_init, str): W_init = initializations.get(weights_init)() W_regul = None if regularizer is not None: W_regul = lambda x: regularizers.get(regularizer)(x, weight_decay) W = va.variable('W', shape=[n_inputs, n_units], regularizer=W_regul, initializer=W_init, trainable=trainable, restore=restore) tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/' + name, W) if isinstance(bias_init, str): bias_init = initializations.get(bias_init)() b = va.variable('b', shape=[n_units], initializer=bias_init, trainable=trainable, restore=restore) tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/' + name, b) # Weight and bias for the transform gate W_T = va.variable('W_T', shape=[n_inputs, n_units], regularizer=None, initializer=W_init, trainable=trainable, restore=restore) tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/' + name, W_T) b_T = va.variable('b_T', shape=[n_units], initializer=tf.constant_initializer(-1), trainable=trainable, restore=restore) tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/' + name, b_T) # If input is not 2d, flatten it. if len(input_shape) > 2: incoming = tf.reshape(incoming, [-1, n_inputs]) if isinstance(activation, str): activation = activations.get(activation) elif hasattr(activation, '__call__'): activation = activation else: raise ValueError("Invalid Activation.") H = activation(tf.matmul(incoming, W) + b) T = tf.sigmoid(tf.matmul(incoming, W_T) + b_T) if transform_dropout: T = dropout(T, transform_dropout) C = tf.subtract(1.0, T) inference = tf.add(tf.multiply(H, T), tf.multiply(incoming, C)) # Track activations. tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, inference) # Add attributes to Tensor to easy access weights. inference.scope = scope inference.W = W inference.W_t = W_T inference.b = b inference.b_t = b_T # Track output tensor. tf.add_to_collection(tf.GraphKeys.LAYER_TENSOR + '/' + name, inference) return inference
def single_unit(incoming, activation='linear', bias=True, trainable=True, restore=True, reuse=False, scope=None, name="Linear"): """ Single Unit. A single unit (Linear) Layer. Input: 1-D Tensor [samples]. If not 2D, input will be flatten. Output: 1-D Tensor [samples]. Arguments: incoming: `Tensor`. Incoming Tensor. activation: `str` (name) or `function`. Activation applied to this layer (see tflearn.activations). Default: 'linear'. bias: `bool`. If True, a bias is used. trainable: `bool`. If True, weights will be trainable. restore: `bool`. If True, this layer weights will be restored when loading a model. reuse: `bool`. If True and 'scope' is provided, this layer variables will be reused (shared). scope: `str`. Define this layer scope (optional). A scope can be used to share variables between layers. Note that scope will override name. name: A name for this layer (optional). Default: 'Linear'. Attributes: W: `Tensor`. Variable representing weight. b: `Tensor`. Variable representing bias. """ input_shape = utils.get_incoming_shape(incoming) n_inputs = int(np.prod(input_shape[1:])) # Build variables and inference. with tf.variable_scope(scope, default_name=name, values=[incoming], reuse=reuse) as scope: name = scope.name W = va.variable('W', shape=[n_inputs], initializer=tf.constant_initializer(np.random.randn()), trainable=trainable, restore=restore) tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/' + name, W) b = None if bias: b = va.variable('b', shape=[n_inputs], initializer=tf.constant_initializer( np.random.randn()), trainable=trainable, restore=restore) tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/' + name, b) inference = incoming # If input is not 2d, flatten it. if len(input_shape) > 1: inference = tf.reshape(inference, [-1]) inference = tf.multiply(inference, W) if b is not None: inference = tf.add(inference, b) if isinstance(activation, str): inference = activations.get(activation)(inference) elif hasattr(activation, '__call__'): inference = activation(inference) else: raise ValueError("Invalid Activation.") # Track activations. tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, inference) # Add attributes to Tensor to easy access weights. inference.scope = scope inference.W = W inference.b = b # Track output tensor. tf.add_to_collection(tf.GraphKeys.LAYER_TENSOR + '/' + name, inference) return inference
def fully_connected(incoming, n_units, activation='linear', bias=True, weights_init='truncated_normal', bias_init='zeros', regularizer=None, weight_decay=0.001, trainable=True, restore=True, reuse=False, scope=None, name="FullyConnected"): """ Fully Connected. A fully connected layer. Input: (2+)-D Tensor [samples, input dim]. If not 2D, input will be flatten. Output: 2D Tensor [samples, n_units]. Arguments: incoming: `Tensor`. Incoming (2+)D Tensor. n_units: `int`, number of units for this layer. activation: `str` (name) or `function` (returning a `Tensor`). Activation applied to this layer (see tflearn.activations). Default: 'linear'. bias: `bool`. If True, a bias is used. weights_init: `str` (name) or `Tensor`. Weights initialization. (see tflearn.initializations) Default: 'truncated_normal'. bias_init: `str` (name) or `Tensor`. Bias initialization. (see tflearn.initializations) Default: 'zeros'. regularizer: `str` (name) or `Tensor`. Add a regularizer to this layer weights (see tflearn.regularizers). Default: None. weight_decay: `float`. Regularizer decay parameter. Default: 0.001. trainable: `bool`. If True, weights will be trainable. restore: `bool`. If True, this layer weights will be restored when loading a model. reuse: `bool`. If True and 'scope' is provided, this layer variables will be reused (shared). scope: `str`. Define this layer scope (optional). A scope can be used to share variables between layers. Note that scope will override name. name: A name for this layer (optional). Default: 'FullyConnected'. Attributes: scope: `Scope`. This layer scope. W: `Tensor`. Variable representing units weights. b: `Tensor`. Variable representing biases. """ input_shape = utils.get_incoming_shape(incoming) assert len(input_shape) > 1, "Incoming Tensor shape must be at least 2-D" n_inputs = int(np.prod(input_shape[1:])) with tf.variable_scope(scope, default_name=name, values=[incoming], reuse=reuse) as scope: name = scope.name W_init = weights_init filter_size = [n_inputs, n_units] if isinstance(weights_init, str): W_init = initializations.get(weights_init)() elif type(W_init) in [tf.Tensor, np.ndarray, list]: filter_size = None W_regul = None if regularizer is not None: W_regul = lambda x: regularizers.get(regularizer)(x, weight_decay) W = va.variable('W', shape=filter_size, regularizer=W_regul, initializer=W_init, trainable=trainable, restore=restore) tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/' + name, W) b = None if bias: b_shape = [n_units] if isinstance(bias_init, str): bias_init = initializations.get(bias_init)() elif type(bias_init) in [tf.Tensor, np.ndarray, list]: b_shape = None if isinstance(bias_init, str): bias_init = initializations.get(bias_init)() b = va.variable('b', shape=b_shape, initializer=bias_init, trainable=trainable, restore=restore) tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/' + name, b) inference = incoming # If input is not 2d, flatten it. if len(input_shape) > 2: inference = tf.reshape(inference, [-1, n_inputs]) inference = tf.matmul(inference, W) if b is not None: inference = tf.nn.bias_add(inference, b) if activation: if isinstance(activation, str): inference = activations.get(activation)(inference) elif hasattr(activation, '__call__'): inference = activation(inference) else: raise ValueError("Invalid Activation.") # Track activations. tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, inference) # Add attributes to Tensor to easy access weights. inference.scope = scope inference.W = W inference.b = b # Track output tensor. tf.add_to_collection(tf.GraphKeys.LAYER_TENSOR + '/' + name, inference) return inference