API - Layers

TensorLayer provides rich layer implementations trailed for various benchmarks and domain-specific problems. In addition, we also support transparent access to native TensorFlow parameters. For example, we provide not only layers for local response normalization, but also layers that allow user to apply tf.nn.lrn on network.outputs. More functions can be found in TensorFlow API.

Understanding the Basic Layer

All TensorLayer layers have a number of properties in common:

  • layer.outputs : a Tensor, the outputs of current layer.
  • layer.all_params : a list of Tensor, all network variables in order.
  • layer.all_layers : a list of Tensor, all network outputs in order.
  • layer.all_drop : a dictionary of {placeholder : float}, all keeping probabilities of noise layers.

All TensorLayer layers have a number of methods in common:

  • layer.print_params() : print network variable information in order (after tl.layers.initialize_global_variables(sess)). alternatively, print all variables by tl.layers.print_all_variables().
  • layer.print_layers() : print network layer information in order.
  • layer.count_params() : print the number of parameters in the network.

A network starts with the input layer and is followed by layers stacked in order. A network is essentially a Layer class. The key properties of a network are network.all_params, network.all_layers and network.all_drop. The all_params is a list which store pointers to all network parameters in order. For example, the following script define a 3 layer network, then:

all_params = [W1, b1, W2, b2, W_out, b_out]

To get specified variable information, you can use network.all_params[2:3] or get_variables_with_name(). all_layers is a list which stores the pointers to the outputs of all layers, see the example as follow:

all_layers = [drop(?,784), relu(?,800), drop(?,800), relu(?,800), drop(?,800)], identity(?,10)]

where ? reflects a given batch size. You can print the layer and parameters information by using network.print_layers() and network.print_params(). To count the number of parameters in a network, run network.count_params().

sess = tf.InteractiveSession()

x = tf.placeholder(tf.float32, shape=[None, 784], name='x')
y_ = tf.placeholder(tf.int64, shape=[None, ], name='y_')

network = tl.layers.InputLayer(x, name='input_layer')
network = tl.layers.DropoutLayer(network, keep=0.8, name='drop1')
network = tl.layers.DenseLayer(network, n_units=800,
                                act = tf.nn.relu, name='relu1')
network = tl.layers.DropoutLayer(network, keep=0.5, name='drop2')
network = tl.layers.DenseLayer(network, n_units=800,
                                act = tf.nn.relu, name='relu2')
network = tl.layers.DropoutLayer(network, keep=0.5, name='drop3')
network = tl.layers.DenseLayer(network, n_units=10,
                                act = tl.activation.identity,
                                name='output_layer')

y = network.outputs
y_op = tf.argmax(tf.nn.softmax(y), 1)

cost = tl.cost.cross_entropy(y, y_)

train_params = network.all_params

train_op = tf.train.AdamOptimizer(learning_rate, beta1=0.9, beta2=0.999,
                            epsilon=1e-08, use_locking=False).minimize(cost, var_list = train_params)

tl.layers.initialize_global_variables(sess)

network.print_params()
network.print_layers()

In addition, network.all_drop is a dictionary which stores the keeping probabilities of all noise layers. In the above network, they represent the keeping probabilities of dropout layers.

In case for training, you can enable all dropout layers as follow:

feed_dict = {x: X_train_a, y_: y_train_a}
feed_dict.update( network.all_drop )
loss, _ = sess.run([cost, train_op], feed_dict=feed_dict)
feed_dict.update( network.all_drop )

In case for evaluating and testing, you can disable all dropout layers as follow.

feed_dict = {x: X_val, y_: y_val}
feed_dict.update(dp_dict)
print("   val loss: %f" % sess.run(cost, feed_dict=feed_dict))
print("   val acc: %f" % np.mean(y_val ==
                        sess.run(y_op, feed_dict=feed_dict)))

For more details, please read the MNIST examples in the example folder.

Customizing Layers

A Simple Layer

To implement a custom layer in TensorLayer, you will have to write a Python class that subclasses Layer and implement the outputs expression.

The following is an example implementation of a layer that multiplies its input by 2:

class DoubleLayer(Layer):
    def __init__(
        self,
        layer = None,
        name ='double_layer',
    ):
        # check layer name (fixed)
        Layer.__init__(self, name=name)

        # the input of this layer is the output of previous layer (fixed)
        self.inputs = layer.outputs

        # operation (customized)
        self.outputs = self.inputs * 2

        # get stuff from previous layer (fixed)
        self.all_layers = list(layer.all_layers)
        self.all_params = list(layer.all_params)
        self.all_drop = dict(layer.all_drop)

        # update layer (customized)
        self.all_layers.append(self.outputs)

Your Dense Layer

Before creating your own TensorLayer layer, let’s have a look at the Dense layer. It creates a weight matrix and a bias vector if not exists, and then implements the output expression. At the end, for a layer with parameters, we also append the parameters into all_params.

class MyDenseLayer(Layer):
  def __init__(
      self,
      layer = None,
      n_units = 100,
      act = tf.nn.relu,
      name ='simple_dense',
  ):
      # check layer name (fixed)
      Layer.__init__(self, name=name)

      # the input of this layer is the output of previous layer (fixed)
      self.inputs = layer.outputs

      # print out info (customized)
      print("  MyDenseLayer %s: %d, %s" % (self.name, n_units, act))

      # operation (customized)
      n_in = int(self.inputs._shape[-1])
      with tf.variable_scope(name) as vs:
          # create new parameters
          W = tf.get_variable(name='W', shape=(n_in, n_units))
          b = tf.get_variable(name='b', shape=(n_units))
          # tensor operation
          self.outputs = act(tf.matmul(self.inputs, W) + b)

      # get stuff from previous layer (fixed)
      self.all_layers = list(layer.all_layers)
      self.all_params = list(layer.all_params)
      self.all_drop = dict(layer.all_drop)

      # update layer (customized)
      self.all_layers.extend( [self.outputs] )
      self.all_params.extend( [W, b] )

Modifying Pre-train Behaviour

Greedy layer-wise pretraining is an important task for deep neural network initialization, while there are many kinds of pre-training methods according to different network architectures and applications.

For example, the pre-train process of Vanilla Sparse Autoencoder can be implemented by using KL divergence (for sigmoid) as the following code, but for Deep Rectifier Network, the sparsity can be implemented by using the L1 regularization of activation output.

# Vanilla Sparse Autoencoder
beta = 4
rho = 0.15
p_hat = tf.reduce_mean(activation_out, reduction_indices = 0)
KLD = beta * tf.reduce_sum( rho * tf.log(tf.div(rho, p_hat))
        + (1- rho) * tf.log((1- rho)/ (tf.sub(float(1), p_hat))) )

There are many pre-train methods, for this reason, TensorLayer provides a simple way to modify or design your own pre-train method. For Autoencoder, TensorLayer uses ReconLayer.__init__() to define the reconstruction layer and cost function, to define your own cost function, just simply modify the self.cost in ReconLayer.__init__(). To creat your own cost expression please read Tensorflow Math. By default, ReconLayer only updates the weights and biases of previous 1 layer by using self.train_params = self.all _params[-4:], where the 4 parameters are [W_encoder, b_encoder, W_decoder, b_decoder], where W_encoder, b_encoder belong to previous DenseLayer, W_decoder, b_decoder belong to this ReconLayer. In addition, if you want to update the parameters of previous 2 layers at the same time, simply modify [-4:] to [-6:].

ReconLayer.__init__(...):
    ...
    self.train_params = self.all_params[-4:]
    ...
      self.cost = mse + L1_a + L2_w

Layer list

get_variables_with_name([name, train_only, …]) Get a list of TensorFlow variables by a given name scope.
get_layers_with_name(net[, name, printable]) Get a list of layers’ output in a network by a given name scope.
set_name_reuse([enable]) DEPRECATED FUNCTION
print_all_variables([train_only]) Print information of trainable or all variables, without tl.layers.initialize_global_variables(sess).
initialize_global_variables(sess) Initialize the global variables of TensorFlow.
Layer([prev_layer, name]) The basic Layer class represents a single layer of a neural network.
InputLayer([inputs, name]) The InputLayer class is the starting layer of a neural network.
OneHotInputLayer([inputs, depth, on_value, …]) The OneHotInputLayer class is the starting layer of a neural network, see tf.one_hot.
Word2vecEmbeddingInputlayer([inputs, …]) The Word2vecEmbeddingInputlayer class is a fully connected layer.
EmbeddingInputlayer([inputs, …]) The EmbeddingInputlayer class is a look-up table for word embedding.
AverageEmbeddingInputlayer(inputs, …[, …]) The AverageEmbeddingInputlayer averages over embeddings of inputs.
DenseLayer(prev_layer[, n_units, act, …]) The DenseLayer class is a fully connected layer.
ReconLayer(prev_layer[, x_recon, n_units, …]) A reconstruction layer for DenseLayer to implement AutoEncoder.
DropoutLayer(prev_layer[, keep, is_fix, …]) The DropoutLayer class is a noise layer which randomly set some activations to zero according to a keeping probability.
GaussianNoiseLayer(prev_layer[, mean, …]) The GaussianNoiseLayer class is noise layer that adding noise with gaussian distribution to the activation.
DropconnectDenseLayer(prev_layer[, keep, …]) The DropconnectDenseLayer class is DenseLayer with DropConnect behaviour which randomly removes connections between this layer and the previous layer according to a keeping probability.
Conv1dLayer(prev_layer[, act, shape, …]) The Conv1dLayer class is a 1D CNN layer, see tf.nn.convolution.
Conv2dLayer(prev_layer[, act, shape, …]) The Conv2dLayer class is a 2D CNN layer, see tf.nn.conv2d.
DeConv2dLayer(prev_layer[, act, shape, …]) A de-convolution 2D layer.
Conv3dLayer(prev_layer[, act, shape, …]) The Conv3dLayer class is a 3D CNN layer, see tf.nn.conv3d.
DeConv3dLayer(prev_layer[, act, shape, …]) The DeConv3dLayer class is deconvolutional 3D layer, see tf.nn.conv3d_transpose.
PoolLayer([prev_layer, ksize, strides, …]) The PoolLayer class is a Pooling layer.
PadLayer(prev_layer, paddings[, mode, name]) The PadLayer class is a padding layer for any mode and dimension.
UpSampling2dLayer(prev_layer, size[, …]) The UpSampling2dLayer class is a up-sampling 2D layer, see tf.image.resize_images.
DownSampling2dLayer(prev_layer, size[, …]) The DownSampling2dLayer class is down-sampling 2D layer, see tf.image.resize_images.
AtrousConv1dLayer(layer[, n_filter, …]) Simplified version of AtrousConv1dLayer.
AtrousConv2dLayer(prev_layer[, n_filter, …]) The AtrousConv2dLayer class is 2D atrous convolution (a.k.a.
Conv1d(layer[, n_filter, filter_size, …]) Simplified version of Conv1dLayer.
Conv2d(layer[, n_filter, filter_size, …]) Simplified version of Conv2dLayer.
DeConv2d(layer[, n_filter, filter_size, …]) Simplified version of DeConv2dLayer.
DeConv3d(prev_layer[, n_filter, …]) Simplified version of The DeConv3dLayer, see tf.contrib.layers.conv3d_transpose.
DepthwiseConv2d(prev_layer[, …]) Separable/Depthwise Convolutional 2D layer, see tf.nn.depthwise_conv2d.
DeformableConv2d(prev_layer[, offset_layer, …]) The DeformableConv2d class is a 2D Deformable Convolutional Networks.
GroupConv2d([prev_layer, n_filter, …]) The GroupConv2d class is 2D grouped convolution, see here.
MaxPool1d(net[, filter_size, strides, …]) Wrapper for tf.layers.max_pooling1d .
MeanPool1d(net[, filter_size, strides, …]) Wrapper for tf.layers.average_pooling1d .
MaxPool2d(net[, filter_size, strides, …]) Wrapper for PoolLayer.
MeanPool2d(net[, filter_size, strides, …]) Wrapper for PoolLayer.
MaxPool3d(prev_layer[, filter_size, …]) Wrapper for tf.layers.max_pooling3d .
MeanPool3d(prev_layer[, filter_size, …]) Wrapper for tf.layers.average_pooling3d
GlobalMaxPool1d([prev_layer, name]) The GlobalMaxPool1d class is a 1D Global Max Pooling layer.
GlobalMeanPool1d([prev_layer, name]) The GlobalMeanPool1d class is a 1D Global Mean Pooling layer.
GlobalMaxPool2d([prev_layer, name]) The GlobalMaxPool2d class is a 2D Global Max Pooling layer.
GlobalMeanPool2d([prev_layer, name]) The GlobalMeanPool2d class is a 2D Global Mean Pooling layer.
SubpixelConv1d(net[, scale, act, name]) It is a 1D sub-pixel up-sampling layer.
SubpixelConv2d(net[, scale, n_out_channel, …]) It is a 2D sub-pixel up-sampling layer, usually be used for Super-Resolution applications, see SRGAN for example.
SpatialTransformer2dAffineLayer([…]) The SpatialTransformer2dAffineLayer class is a 2D Spatial Transformer Layer for 2D Affine Transformation.
transformer(U, theta, out_size[, name]) Spatial Transformer Layer for 2D Affine Transformation , see SpatialTransformer2dAffineLayer class.
batch_transformer(U, thetas, out_size[, name]) Batch Spatial Transformer function for 2D Affine Transformation.
BatchNormLayer(prev_layer[, decay, epsilon, …]) The BatchNormLayer is a batch normalization layer for both fully-connected and convolution outputs.
LocalResponseNormLayer(prev_layer[, …]) The LocalResponseNormLayer layer is for Local Response Normalization.
InstanceNormLayer(prev_layer[, act, …]) The InstanceNormLayer class is a for instance normalization.
LayerNormLayer(prev_layer[, center, scale, …]) The LayerNormLayer class is for layer normalization, see tf.contrib.layers.layer_norm.
ROIPoolingLayer(prev_layer, rois[, …]) The region of interest pooling layer.
TimeDistributedLayer(prev_layer[, …]) The TimeDistributedLayer class that applies a function to every timestep of the input tensor.
RNNLayer(prev_layer, cell_fn[, …]) The RNNLayer class is a fixed length recurrent layer for implementing vanilla RNN, LSTM, GRU and etc.
BiRNNLayer(prev_layer, cell_fn[, …]) The BiRNNLayer class is a fixed length Bidirectional recurrent layer.
ConvRNNCell Abstract object representing an Convolutional RNN Cell.
BasicConvLSTMCell(shape, filter_size, …[, …]) Basic Conv LSTM recurrent network cell.
ConvLSTMLayer(prev_layer[, cell_shape, …]) A fixed length Convolutional LSTM layer.
advanced_indexing_op(inputs, index) Advanced Indexing for Sequences, returns the outputs by given sequence lengths.
retrieve_seq_length_op(data) An op to compute the length of a sequence from input shape of [batch_size, n_step(max), n_features], it can be used when the features of padding (on right hand side) are all zeros.
retrieve_seq_length_op2(data) An op to compute the length of a sequence, from input shape of [batch_size, n_step(max)], it can be used when the features of padding (on right hand side) are all zeros.
retrieve_seq_length_op3(data[, pad_val]) Return tensor for sequence length, if input is tf.string.
target_mask_op(data[, pad_val]) Return tensor for mask, if input is tf.string.
DynamicRNNLayer(prev_layer, cell_fn[, …]) The DynamicRNNLayer class is a dynamic recurrent layer, see tf.nn.dynamic_rnn.
BiDynamicRNNLayer(prev_layer, cell_fn[, …]) The BiDynamicRNNLayer class is a RNN layer, you can implement vanilla RNN, LSTM and GRU with it.
Seq2Seq(net_encode_in, net_decode_in, cell_fn) The Seq2Seq class is a simple DynamicRNNLayer based Seq2seq layer without using tl.contrib.seq2seq.
FlattenLayer(prev_layer[, name]) A layer that reshapes high-dimension input into a vector.
ReshapeLayer(prev_layer, shape[, name]) A layer that reshapes a given tensor.
TransposeLayer(prev_layer, perm[, name]) A layer that transposes the dimension of a tensor.
LambdaLayer(prev_layer, fn[, fn_args, name]) A layer that takes a user-defined function using TensorFlow Lambda.
ConcatLayer(layers[, concat_dim, name]) A layer that concats multiple tensors according to given axis..
ElementwiseLayer(layers[, combine_fn, act, name]) A layer that combines multiple Layer that have the same output shapes according to an element-wise operation.
ExpandDimsLayer(prev_layer, axis[, name]) The ExpandDimsLayer class inserts a dimension of 1 into a tensor’s shape, see tf.expand_dims() .
TileLayer([prev_layer, multiples, name]) The TileLayer class constructs a tensor by tiling a given tensor, see tf.tile() .
StackLayer(layers[, axis, name]) The StackLayer class is layer for stacking a list of rank-R tensors into one rank-(R+1) tensor, see tf.stack().
UnStackLayer(layer[, num, axis, name]) It is layer for unstacking the given dimension of a rank-R tensor into rank-(R-1) tensors., see tf.unstack().
SlimNetsLayer(prev_layer, slim_layer[, …]) A layer that merges TF-Slim models into TensorLayer.
PReluLayer(prev_layer[, channel_shared, …]) The PReluLayer class is Parametric Rectified Linear layer.
MultiplexerLayer(layers[, name]) The MultiplexerLayer selects inputs to be forwarded to output.
flatten_reshape(variable[, name]) Reshapes a high-dimension vector input.
clear_layers_name() DEPRECATED FUNCTION
initialize_rnn_state(state[, feed_dict]) Returns the initialized RNN state.
list_remove_repeat(x) Remove the repeated items in a list, and return the processed list.
merge_networks([layers]) Merge all parameters, layers and dropout probabilities to a Layer.

Name Scope and Sharing Parameters

These functions help you to reuse parameters for different inference (graph), and get a list of parameters by given name. About TensorFlow parameters sharing click here.

Get variables with name

tensorlayer.layers.get_variables_with_name(name=None, train_only=True, printable=False)[source]

Get a list of TensorFlow variables by a given name scope.

Parameters:
  • name (str) – Get the variables that contain this name.
  • train_only (boolean) – If Ture, only get the trainable variables.
  • printable (boolean) – If True, print the information of all variables.
Returns:

A list of TensorFlow variables

Return type:

list of Tensor

Examples

>>> dense_vars = tl.layers.get_variable_with_name('dense', True, True)

Get layers with name

tensorlayer.layers.get_layers_with_name(net, name='', printable=False)[source]

Get a list of layers’ output in a network by a given name scope.

Parameters:
  • net (Layer) – The last layer of the network.
  • name (str) – Get the layers’ output that contain this name.
  • printable (boolean) – If True, print information of all the layers’ output
Returns:

A list of layers’ output (TensorFlow tensor)

Return type:

list of Tensor

Examples

>>> layers = tl.layers.get_layers_with_name(net, "CNN", True)

Enable layer name reuse

tensorlayer.layers.set_name_reuse(enable=True)[source]

DEPRECATED FUNCTION

THIS FUNCTION IS DEPRECATED. It will be removed after 2018-06-30. Instructions for updating: TensorLayer relies on TensorFlow to check name reusing.

Initialize variables

tensorlayer.layers.initialize_global_variables(sess)[source]

Initialize the global variables of TensorFlow.

Run sess.run(tf.global_variables_initializer()) for TF 0.12+ or sess.run(tf.initialize_all_variables()) for TF 0.11.

Parameters:sess (Session) – TensorFlow session.

Basic layer

class tensorlayer.layers.Layer(prev_layer=None, name=None)[source]

The basic Layer class represents a single layer of a neural network. It should be subclassed when implementing new types of layers. Because each layer can keep track of the layer(s) feeding into it, a network’s output Layer instance can double as a handle to the full network.

Parameters:
  • inputs (Layer instance) – The Layer class feeding into this layer.
  • layer (Layer or None) – Previous layer (optional), for adding all properties of previous layer(s) to this layer.
  • name (str or None) – A unique layer name.
print_params(details=True, session=None)[source]

Print all parameters of this network.

print_layers()[source]

Print all outputs of all layers of this network.

count_params()[source]

Return the number of parameters of this network.

Examples

  • Define model
>>> x = tf.placeholder("float32", [None, 100])
>>> n = tl.layers.InputLayer(x, name='in')
>>> n = tl.layers.DenseLayer(n, 80, name='d1')
>>> n = tl.layers.DenseLayer(n, 80, name='d2')
  • Get information
>>> print(n)
... Last layer is: DenseLayer (d2) [None, 80]
>>> n.print_layers()
... [TL]   layer   0: d1/Identity:0        (?, 80)            float32
... [TL]   layer   1: d2/Identity:0        (?, 80)            float32
>>> n.print_params(False)
... [TL]   param   0: d1/W:0               (100, 80)          float32_ref
... [TL]   param   1: d1/b:0               (80,)              float32_ref
... [TL]   param   2: d2/W:0               (80, 80)           float32_ref
... [TL]   param   3: d2/b:0               (80,)              float32_ref
... [TL]   num of params: 14560
>>> n.count_params()
... 14560
  • Slicing the outputs
>>> n2 = n[:, :30]
>>> print(n2)
... Last layer is: Layer (d2) [None, 30]
  • Iterating the outputs
>>> for l in n:
>>>    print(l)
... Tensor("d1/Identity:0", shape=(?, 80), dtype=float32)
... Tensor("d2/Identity:0", shape=(?, 80), dtype=float32)

Input layer

class tensorlayer.layers.InputLayer(inputs=None, name='input')[source]

The InputLayer class is the starting layer of a neural network.

Parameters:
  • inputs (placeholder or tensor) – The input of a network.
  • name (str) – A unique layer name.

One-hot layer

class tensorlayer.layers.OneHotInputLayer(inputs=None, depth=None, on_value=None, off_value=None, axis=None, dtype=None, name='input')[source]

The OneHotInputLayer class is the starting layer of a neural network, see tf.one_hot.

Parameters:
  • inputs (placeholder or tensor) – The input of a network.
  • depth (None or int) – If the input indices is rank N, the output will have rank N+1. The new axis is created at dimension axis (default: the new axis is appended at the end).
  • on_value (None or number) – The value to represnt ON. If None, it will default to the value 1.
  • off_value (None or number) – The value to represnt OFF. If None, it will default to the value 0.
  • axis (None or int) – The axis.
  • dtype (None or TensorFlow dtype) – The data type, None means tf.float32.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder(tf.int32, shape=[None])
>>> net = tl.layers.OneHotInputLayer(x, depth=8, name='onehot')
... (?, 8)

Word Embedding Input layer

Word2vec layer for training

class tensorlayer.layers.Word2vecEmbeddingInputlayer(inputs=None, train_labels=None, vocabulary_size=80000, embedding_size=200, num_sampled=64, nce_loss_args=None, E_init=<tensorflow.python.ops.init_ops.RandomUniform object>, E_init_args=None, nce_W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, nce_W_init_args=None, nce_b_init=<tensorflow.python.ops.init_ops.Constant object>, nce_b_init_args=None, name='word2vec')[source]

The Word2vecEmbeddingInputlayer class is a fully connected layer. For Word Embedding, words are input as integer index. The output is the embedded word vector.

Parameters:
  • inputs (placeholder or tensor) – The input of a network. For word inputs, please use integer index format, 2D tensor : [batch_size, num_steps(num_words)]
  • train_labels (placeholder) – For word labels. integer index format
  • vocabulary_size (int) – The size of vocabulary, number of words
  • embedding_size (int) – The number of embedding dimensions
  • num_sampled (int) – The mumber of negative examples for NCE loss
  • nce_loss_args (dictionary) – The arguments for tf.nn.nce_loss()
  • E_init (initializer) – The initializer for initializing the embedding matrix
  • E_init_args (dictionary) – The arguments for embedding initializer
  • nce_W_init (initializer) – The initializer for initializing the nce decoder weight matrix
  • nce_W_init_args (dictionary) – The arguments for initializing the nce decoder weight matrix
  • nce_b_init (initializer) – The initializer for initializing of the nce decoder bias vector
  • nce_b_init_args (dictionary) – The arguments for initializing the nce decoder bias vector
  • name (str) – A unique layer name
nce_cost

Tensor – The NCE loss.

outputs

Tensor – The embedding layer outputs.

normalized_embeddings

Tensor – Normalized embedding matrix.

Examples

With TensorLayer : see tensorlayer/example/tutorial_word2vec_basic.py

>>> batch_size = 8
>>> train_inputs = tf.placeholder(tf.int32, shape=(batch_size))
>>> train_labels = tf.placeholder(tf.int32, shape=(batch_size, 1))
>>> net = tl.layers.Word2vecEmbeddingInputlayer(inputs=train_inputs,
...     train_labels=train_labels, vocabulary_size=1000, embedding_size=200,
...     num_sampled=64, name='word2vec')
... (8, 200)
>>> cost = net.nce_cost
>>> train_params = net.all_params
>>> cost = net.nce_cost
>>> train_params = net.all_params
>>> train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(
...                                             cost, var_list=train_params)
>>> normalized_embeddings = net.normalized_embeddings

Without TensorLayer : see tensorflow/examples/tutorials/word2vec/word2vec_basic.py

>>> train_inputs = tf.placeholder(tf.int32, shape=(batch_size))
>>> train_labels = tf.placeholder(tf.int32, shape=(batch_size, 1))
>>> embeddings = tf.Variable(
...     tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
>>> embed = tf.nn.embedding_lookup(embeddings, train_inputs)
>>> nce_weights = tf.Variable(
...     tf.truncated_normal([vocabulary_size, embedding_size],
...                    stddev=1.0 / math.sqrt(embedding_size)))
>>> nce_biases = tf.Variable(tf.zeros([vocabulary_size]))
>>> cost = tf.reduce_mean(
...    tf.nn.nce_loss(weights=nce_weights, biases=nce_biases,
...               inputs=embed, labels=train_labels,
...               num_sampled=num_sampled, num_classes=vocabulary_size,
...               num_true=1))

References

tensorflow/examples/tutorials/word2vec/word2vec_basic.py

Embedding Input layer

class tensorlayer.layers.EmbeddingInputlayer(inputs=None, vocabulary_size=80000, embedding_size=200, E_init=<tensorflow.python.ops.init_ops.RandomUniform object>, E_init_args=None, name='embedding')[source]

The EmbeddingInputlayer class is a look-up table for word embedding.

Word content are accessed using integer indexes, then the output is the embedded word vector. To train a word embedding matrix, you can used Word2vecEmbeddingInputlayer. If you have a pre-trained matrix, you can assign the parameters into it.

Parameters:
  • inputs (placeholder) – The input of a network. For word inputs. Please use integer index format, 2D tensor : (batch_size, num_steps(num_words)).
  • vocabulary_size (int) – The size of vocabulary, number of words.
  • embedding_size (int) – The number of embedding dimensions.
  • E_init (initializer) – The initializer for the embedding matrix.
  • E_init_args (dictionary) – The arguments for embedding matrix initializer.
  • name (str) – A unique layer name.
outputs

tensor – The embedding layer output is a 3D tensor in the shape: (batch_size, num_steps(num_words), embedding_size).

Examples

>>> batch_size = 8
>>> x = tf.placeholder(tf.int32, shape=(batch_size, ))
>>> net = tl.layers.EmbeddingInputlayer(inputs=x, vocabulary_size=1000, embedding_size=50, name='embed')
... (8, 50)

Average Embedding Input layer

class tensorlayer.layers.AverageEmbeddingInputlayer(inputs, vocabulary_size, embedding_size, pad_value=0, embeddings_initializer=<tensorflow.python.ops.init_ops.RandomUniform object>, embeddings_kwargs=None, name='average_embedding')[source]

The AverageEmbeddingInputlayer averages over embeddings of inputs. This is often used as the input layer for models like DAN[1] and FastText[2].

Parameters:
  • inputs (placeholder or tensor) – The network input. For word inputs, please use integer index format, 2D tensor: (batch_size, num_steps(num_words)).
  • vocabulary_size (int) – The size of vocabulary.
  • embedding_size (int) – The dimension of the embedding vectors.
  • pad_value (int) – The scalar padding value used in inputs, 0 as default.
  • embeddings_initializer (initializer) – The initializer of the embedding matrix.
  • embeddings_kwargs (None or dictionary) – The arguments to get embedding matrix variable.
  • name (str) – A unique layer name.

References

  • [1] Iyyer, M., Manjunatha, V., Boyd-Graber, J., & Daum’e III, H. (2015). Deep Unordered Composition Rivals Syntactic Methods for Text Classification. In Association for Computational Linguistics.
  • [2] Joulin, A., Grave, E., Bojanowski, P., & Mikolov, T. (2016). Bag of Tricks for Efficient Text Classification.

Examples

>>> batch_size = 8
>>> length = 5
>>> x = tf.placeholder(tf.int32, shape=(batch_size, length))
>>> net = tl.layers.AverageEmbeddingInputlayer(x, vocabulary_size=1000, embedding_size=50, name='avg')
... (8, 50)

Dense layer

Dense layer

class tensorlayer.layers.DenseLayer(prev_layer, n_units=100, act=<function identity>, W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, name='dense')[source]

The DenseLayer class is a fully connected layer.

Parameters:
  • layer (Layer) – Previous layer.
  • n_units (int) – The number of units of this layer.
  • act (activation function) – The activation function of this layer.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer or None) – The initializer for the bias vector. If None, skip biases.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • name (a str) – A unique layer name.

Examples

With TensorLayer

>>> net = tl.layers.InputLayer(x, name='input')
>>> net = tl.layers.DenseLayer(net, 800, act=tf.nn.relu, name='relu')

Without native TensorLayer APIs, you can do as follow.

>>> W = tf.Variable(
...     tf.random_uniform([n_in, n_units], -1.0, 1.0), name='W')
>>> b = tf.Variable(tf.zeros(shape=[n_units]), name='b')
>>> y = tf.nn.relu(tf.matmul(inputs, W) + b)

Notes

If the layer input has more than two axes, it needs to be flatten by using FlattenLayer.

Reconstruction layer for Autoencoder

class tensorlayer.layers.ReconLayer(prev_layer, x_recon=None, n_units=784, act=<function softplus>, name='recon')[source]

A reconstruction layer for DenseLayer to implement AutoEncoder.

It is often used to pre-train the previous DenseLayer

Parameters:
  • layer (Layer) – Previous layer.
  • x_recon (placeholder or tensor) – The target for reconstruction.
  • n_units (int) – The number of units of the layer. It should equal x_recon.
  • act (activation function) – The activation function of this layer. Normally, for sigmoid layer, the reconstruction activation is sigmoid; for rectifying layer, the reconstruction activation is softplus.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder(tf.float32, shape=(None, 784))
>>> net = tl.layers.InputLayer(x, name='input')
>>> net = tl.layers.DenseLayer(net, n_units=196, act=tf.nn.sigmoid, name='dense')
>>> recon = tl.layers.ReconLayer(net, x_recon=x, n_units=784, act=tf.nn.sigmoid, name='recon')
>>> sess = tf.InteractiveSession()
>>> tl.layers.initialize_global_variables(sess)
>>> X_train, y_train, X_val, y_val, X_test, y_test = tl.files.load_mnist_dataset(shape=(-1, 784))
>>> recon.pretrain(sess, x=x, X_train=X_train, X_val=X_val, denoise_name=None, n_epoch=500, batch_size=128, print_freq=1, save=True, save_name='w1pre_')
pretrain(sess, x, X_train, X_val, denoise_name=None, n_epoch=100, batch_size=128, print_freq=10, save=True, save_name='w1pre')[source]

Start to pre-train the parameters of the previous DenseLayer.

Notes

The input layer should be DenseLayer or a layer that has only one axes. You may need to modify this part to define your own cost function. By default, the cost is implemented as follow: - For sigmoid layer, the implementation can be UFLDL - For rectifying layer, the implementation can be Glorot (2011). Deep Sparse Rectifier Neural Networks

Noise layer

Dropout layer

class tensorlayer.layers.DropoutLayer(prev_layer, keep=0.5, is_fix=False, is_train=True, seed=None, name='dropout_layer')[source]

The DropoutLayer class is a noise layer which randomly set some activations to zero according to a keeping probability.

Parameters:
  • layer (Layer) – Previous layer.
  • keep (float) – The keeping probability. The lower the probability it is, the more activations are set to zero.
  • is_fix (boolean) – Fixing probability or nor. Default is False. If True, the keeping probability is fixed and cannot be changed via feed_dict.
  • is_train (boolean) – Trainable or not. If False, skip this layer. Default is True.
  • seed (int or None) – The seed for random dropout.
  • name (str) – A unique layer name.

Examples

Method 1: Using all_drop see tutorial_mlp_dropout1.py

>>> net = tl.layers.InputLayer(x, name='input_layer')
>>> net = tl.layers.DropoutLayer(net, keep=0.8, name='drop1')
>>> net = tl.layers.DenseLayer(net, n_units=800, act=tf.nn.relu, name='relu1')
>>> ...
>>> # For training, enable dropout as follow.
>>> feed_dict = {x: X_train_a, y_: y_train_a}
>>> feed_dict.update( net.all_drop )     # enable noise layers
>>> sess.run(train_op, feed_dict=feed_dict)
>>> ...
>>> # For testing, disable dropout as follow.
>>> dp_dict = tl.utils.dict_to_one( net.all_drop ) # disable noise layers
>>> feed_dict = {x: X_val_a, y_: y_val_a}
>>> feed_dict.update(dp_dict)
>>> err, ac = sess.run([cost, acc], feed_dict=feed_dict)
>>> ...

Method 2: Without using all_drop see tutorial_mlp_dropout2.py

>>> def mlp(x, is_train=True, reuse=False):
>>>     with tf.variable_scope("MLP", reuse=reuse):
>>>     tl.layers.set_name_reuse(reuse)
>>>     net = tl.layers.InputLayer(x, name='input')
>>>     net = tl.layers.DropoutLayer(net, keep=0.8, is_fix=True,
>>>                         is_train=is_train, name='drop1')
>>>     ...
>>>     return net
>>> # define inferences
>>> net_train = mlp(x, is_train=True, reuse=False)
>>> net_test = mlp(x, is_train=False, reuse=True)

Gaussian noise layer

class tensorlayer.layers.GaussianNoiseLayer(prev_layer, mean=0.0, stddev=1.0, is_train=True, seed=None, name='gaussian_noise_layer')[source]

The GaussianNoiseLayer class is noise layer that adding noise with gaussian distribution to the activation.

Parameters:
  • layer (Layer) – Previous layer.
  • mean (float) – The mean. Default is 0.
  • stddev (float) – The standard deviation. Default is 1.
  • is_train (boolean) – Is trainable layer. If False, skip this layer. default is True.
  • seed (int or None) – The seed for random noise.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder(tf.float32, shape=(100, 784))
>>> net = tl.layers.InputLayer(x, name='input')
>>> net = tl.layers.DenseLayer(net, n_units=100, act=tf.nn.relu, name='dense3')
>>> net = tl.layers.GaussianNoiseLayer(net, name='gaussian')
... (64, 100)

Dropconnect + Dense layer

class tensorlayer.layers.DropconnectDenseLayer(prev_layer, keep=0.5, n_units=100, act=<function identity>, W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, name='dropconnect_layer')[source]

The DropconnectDenseLayer class is DenseLayer with DropConnect behaviour which randomly removes connections between this layer and the previous layer according to a keeping probability.

Parameters:
  • layer (Layer) – Previous layer.
  • keep (float) – The keeping probability. The lower the probability it is, the more activations are set to zero.
  • n_units (int) – The number of units of this layer.
  • act (activation function) – The activation function of this layer.
  • W_init (weights initializer) – The initializer for the weight matrix.
  • b_init (biases initializer) – The initializer for the bias vector.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • name (str) – A unique layer name.

Examples

>>> net = tl.layers.InputLayer(x, name='input_layer')
>>> net = tl.layers.DropconnectDenseLayer(net, keep=0.8,
...         n_units=800, act=tf.nn.relu, name='relu1')
>>> net = tl.layers.DropconnectDenseLayer(net, keep=0.5,
...         n_units=800, act=tf.nn.relu, name='relu2')
>>> net = tl.layers.DropconnectDenseLayer(net, keep=0.5,
...         n_units=10, name='output')

References

Convolutional layer (Pro)

1D Convolution

class tensorlayer.layers.Conv1dLayer(prev_layer, act=<function identity>, shape=(5, 1, 5), stride=1, dilation_rate=1, padding='SAME', data_format='NWC', W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, name='cnn1d')[source]

The Conv1dLayer class is a 1D CNN layer, see tf.nn.convolution.

Parameters:
  • layer (Layer) – Previous layer.
  • act (activation function) – The activation function of this layer.
  • shape (tuple of int) – The shape of the filters: (filter_length, in_channels, out_channels).
  • stride (int) – The number of entries by which the filter is moved right at a step.
  • dilation_rate (int) – Filter up-sampling/input down-sampling rate.
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • data_format (str) – Default is ‘NWC’ as it is a 1D CNN.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer or None) – The initializer for the bias vector. If None, skip biases.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • name (str) – A unique layer name

2D Convolution

class tensorlayer.layers.Conv2dLayer(prev_layer, act=<function identity>, shape=(5, 5, 1, 100), strides=(1, 1, 1, 1), padding='SAME', W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, use_cudnn_on_gpu=None, data_format=None, name='cnn_layer')[source]

The Conv2dLayer class is a 2D CNN layer, see tf.nn.conv2d.

Parameters:
  • layer (Layer) – Previous layer.
  • act (activation function) – The activation function of this layer.
  • shape (tuple of int) – The shape of the filters: (filter_height, filter_width, in_channels, out_channels).
  • strides (tuple of int) – The sliding window strides of corresponding input dimensions. It must be in the same order as the shape parameter.
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • W_init (initializer) – The initializer for the the weight matrix.
  • b_init (initializer or None) – The initializer for the the bias vector. If None, skip biases.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • use_cudnn_on_gpu (bool) – Default is False.
  • data_format (str) – “NHWC” or “NCHW”, default is “NHWC”.
  • name (str) – A unique layer name.

Notes

  • shape = [h, w, the number of output channel of previous layer, the number of output channels]
  • the number of output channel of a layer is its last dimension.

Examples

With TensorLayer

>>> x = tf.placeholder(tf.float32, shape=(None, 28, 28, 1))
>>> net = tl.layers.InputLayer(x, name='input_layer')
>>> net = tl.layers.Conv2dLayer(net,
...                   act = tf.nn.relu,
...                   shape = (5, 5, 1, 32),  # 32 features for each 5x5 patch
...                   strides = (1, 1, 1, 1),
...                   padding='SAME',
...                   W_init=tf.truncated_normal_initializer(stddev=5e-2),
...                   b_init = tf.constant_initializer(value=0.0),
...                   name ='cnn_layer1')     # output: (?, 28, 28, 32)
>>> net = tl.layers.PoolLayer(net,
...                   ksize=(1, 2, 2, 1),
...                   strides=(1, 2, 2, 1),
...                   padding='SAME',
...                   pool = tf.nn.max_pool,
...                   name ='pool_layer1',)   # output: (?, 14, 14, 32)

Without TensorLayer, you can implement 2D convolution as follow.

>>> W = tf.Variable(W_init(shape=[5, 5, 1, 32], ), name='W_conv')
>>> b = tf.Variable(b_init(shape=[32], ), name='b_conv')
>>> outputs = tf.nn.relu( tf.nn.conv2d(inputs, W,
...                       strides=[1, 1, 1, 1],
...                       padding='SAME') + b )

2D Deconvolution

class tensorlayer.layers.DeConv2dLayer(prev_layer, act=<function identity>, shape=(3, 3, 128, 256), output_shape=(1, 256, 256, 128), strides=(1, 2, 2, 1), padding='SAME', W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, name='decnn2d_layer')[source]

A de-convolution 2D layer.

See tf.nn.conv2d_transpose.

Parameters:
  • layer (Layer) – Previous layer.
  • act (activation function) – The activation function of this layer.
  • shape (tuple of int) – Shape of the filters: (height, width, output_channels, in_channels). The filter’s in_channels dimension must match that of value.
  • output_shape (tuple of int) – Output shape of the deconvolution,
  • strides (tuple of int) – The sliding window strides for corresponding input dimensions.
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer or None) – The initializer for the bias vector. If None, skip biases.
  • W_init_args (dictionary) – The arguments for initializing the weight matrix.
  • b_init_args (dictionary) – The arguments for initializing the bias vector.
  • name (str) – A unique layer name.

Notes

  • We recommend to use DeConv2d with TensorFlow version higher than 1.3.
  • shape = [h, w, the number of output channels of this layer, the number of output channel of the previous layer].
  • output_shape = [batch_size, any, any, the number of output channels of this layer].
  • the number of output channel of a layer is its last dimension.

Examples

A part of the generator in DCGAN example

>>> batch_size = 64
>>> inputs = tf.placeholder(tf.float32, [batch_size, 100], name='z_noise')
>>> net_in = tl.layers.InputLayer(inputs, name='g/in')
>>> net_h0 = tl.layers.DenseLayer(net_in, n_units = 8192,
...                            W_init = tf.random_normal_initializer(stddev=0.02),
...                            act = tf.identity, name='g/h0/lin')
>>> print(net_h0.outputs._shape)
... (64, 8192)
>>> net_h0 = tl.layers.ReshapeLayer(net_h0, shape=(-1, 4, 4, 512), name='g/h0/reshape')
>>> net_h0 = tl.layers.BatchNormLayer(net_h0, act=tf.nn.relu, is_train=is_train, name='g/h0/batch_norm')
>>> print(net_h0.outputs._shape)
... (64, 4, 4, 512)
>>> net_h1 = tl.layers.DeConv2dLayer(net_h0,
...                            shape=(5, 5, 256, 512),
...                            output_shape=(batch_size, 8, 8, 256),
...                            strides=(1, 2, 2, 1),
...                            act=tf.identity, name='g/h1/decon2d')
>>> net_h1 = tl.layers.BatchNormLayer(net_h1, act=tf.nn.relu, is_train=is_train, name='g/h1/batch_norm')
>>> print(net_h1.outputs._shape)
... (64, 8, 8, 256)

U-Net

>>> ....
>>> conv10 = tl.layers.Conv2dLayer(conv9, act=tf.nn.relu,
...        shape=(3,3,1024,1024), strides=(1,1,1,1), padding='SAME',
...        W_init=w_init, b_init=b_init, name='conv10')
>>> print(conv10.outputs)
... (batch_size, 32, 32, 1024)
>>> deconv1 = tl.layers.DeConv2dLayer(conv10, act=tf.nn.relu,
...         shape=(3,3,512,1024), strides=(1,2,2,1), output_shape=(batch_size,64,64,512),
...         padding='SAME', W_init=w_init, b_init=b_init, name='devcon1_1')

3D Convolution

class tensorlayer.layers.Conv3dLayer(prev_layer, act=<function identity>, shape=(2, 2, 2, 3, 32), strides=(1, 2, 2, 2, 1), padding='SAME', W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, name='cnn3d_layer')[source]

The Conv3dLayer class is a 3D CNN layer, see tf.nn.conv3d.

Parameters:
  • layer (Layer) – Previous layer.
  • act (activation function) – The activation function of this layer.
  • shape (tuple of int) – Shape of the filters: (filter_depth, filter_height, filter_width, in_channels, out_channels).
  • strides (tuple of int) – The sliding window strides for corresponding input dimensions. Must be in the same order as the shape dimension.
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer) – The initializer for the bias vector.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder(tf.float32, (None, 100, 100, 100, 3))
>>> n = tl.layers.InputLayer(x, name='in3')
>>> n = tl.layers.Conv3dLayer(n, shape=(2, 2, 2, 3, 32), strides=(1, 2, 2, 2, 1))
... [None, 50, 50, 50, 32]

3D Deconvolution

class tensorlayer.layers.DeConv3dLayer(prev_layer, act=<function identity>, shape=(2, 2, 2, 128, 256), output_shape=(1, 12, 32, 32, 128), strides=(1, 2, 2, 2, 1), padding='SAME', W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, name='decnn3d_layer')[source]

The DeConv3dLayer class is deconvolutional 3D layer, see tf.nn.conv3d_transpose.

Parameters:
  • layer (Layer) – Previous layer.
  • act (activation function) – The activation function of this layer.
  • shape (tuple of int) – The shape of the filters: (depth, height, width, output_channels, in_channels). The filter’s in_channels dimension must match that of value.
  • output_shape (tuple of int) – The output shape of the deconvolution.
  • strides (tuple of int) – The sliding window strides for corresponding input dimensions.
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer) – The initializer for the bias vector.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • name (str) – A unique layer name.

2D UpSampling

class tensorlayer.layers.UpSampling2dLayer(prev_layer, size, is_scale=True, method=0, align_corners=False, name='upsample2d_layer')[source]

The UpSampling2dLayer class is a up-sampling 2D layer, see tf.image.resize_images.

Parameters:
  • layer (Layer) – Previous layer with 4-D Tensor of the shape (batch, height, width, channels) or 3-D Tensor of the shape (height, width, channels).
  • size (tuple of int/float) – (height, width) scale factor or new size of height and width.
  • is_scale (boolean) – If True (default), the size is a scale factor; otherwise, the size is the numbers of pixels of height and width.
  • method (int) –
    The resize method selected through the index. Defaults index is 0 which is ResizeMethod.BILINEAR.
    • Index 0 is ResizeMethod.BILINEAR, Bilinear interpolation.
    • Index 1 is ResizeMethod.NEAREST_NEIGHBOR, Nearest neighbor interpolation.
    • Index 2 is ResizeMethod.BICUBIC, Bicubic interpolation.
    • Index 3 ResizeMethod.AREA, Area interpolation.
  • align_corners (boolean) – If True, align the corners of the input and output. Default is False.
  • name (str) – A unique layer name.

2D DownSampling

class tensorlayer.layers.DownSampling2dLayer(prev_layer, size, is_scale=True, method=0, align_corners=False, name='downsample2d_layer')[source]

The DownSampling2dLayer class is down-sampling 2D layer, see tf.image.resize_images.

Parameters:
  • layer (Layer) – Previous layer with 4-D Tensor in the shape of (batch, height, width, channels) or 3-D Tensor in the shape of (height, width, channels).
  • size (tuple of int/float) – (height, width) scale factor or new size of height and width.
  • is_scale (boolean) – If True (default), the size is the scale factor; otherwise, the size are numbers of pixels of height and width.
  • method (int) –
    The resize method selected through the index. Defaults index is 0 which is ResizeMethod.BILINEAR.
    • Index 0 is ResizeMethod.BILINEAR, Bilinear interpolation.
    • Index 1 is ResizeMethod.NEAREST_NEIGHBOR, Nearest neighbor interpolation.
    • Index 2 is ResizeMethod.BICUBIC, Bicubic interpolation.
    • Index 3 ResizeMethod.AREA, Area interpolation.
  • align_corners (boolean) – If True, exactly align all 4 corners of the input and output. Default is False.
  • name (str) – A unique layer name.

1D Atrous convolution

tensorlayer.layers.AtrousConv1dLayer(layer, n_filter=32, filter_size=2, stride=1, dilation=1, act=<function identity>, padding='SAME', data_format='NWC', W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, name='conv1d')

Simplified version of AtrousConv1dLayer.

Parameters:
  • layer (Layer) – Previous layer.
  • n_filter (int) – The number of filters.
  • filter_size (int) – The filter size.
  • stride (tuple of int) – The strides: (height, width).
  • dilation (int) – The filter dilation size.
  • act (activation function) – The activation function of this layer.
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • data_format (str) – Default is ‘NWC’ as it is a 1D CNN.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer or None) – The initializer for the bias vector. If None, skip biases.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • name (str) – A unique layer name.
Returns:

A AtrousConv1dLayer object

Return type:

Layer

2D Atrous convolution

class tensorlayer.layers.AtrousConv2dLayer(prev_layer, n_filter=32, filter_size=(3, 3), rate=2, act=<function identity>, padding='SAME', W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, name='atrou2d')[source]

The AtrousConv2dLayer class is 2D atrous convolution (a.k.a. convolution with holes or dilated convolution) 2D layer, see tf.nn.atrous_conv2d.

Parameters:
  • layer (Layer) – Previous layer with a 4D output tensor in the shape of (batch, height, width, channels).
  • n_filter (int) – The number of filters.
  • filter_size (tuple of int) – The filter size: (height, width).
  • rate (int) – The stride that we sample input values in the height and width dimensions. This equals the rate that we up-sample the filters by inserting zeros across the height and width dimensions. In the literature, this parameter is sometimes mentioned as input stride or dilation.
  • act (activation function) – The activation function of this layer.
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer or None) – The initializer for the bias vector. If None, skip biases.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • name (str) – A unique layer name.

Convolutional layer (Simplified)

For users don’t familiar with TensorFlow, the following simplified functions may easier for you. We will provide more simplified functions later, but if you are good at TensorFlow, the professional APIs may better for you.

1D Convolution

tensorlayer.layers.Conv1d(layer, n_filter=32, filter_size=5, stride=1, dilation_rate=1, act=<function identity>, padding='SAME', data_format='NWC', W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, name='conv1d')

Simplified version of Conv1dLayer.

Parameters:
  • layer (Layer) – Previous layer
  • n_filter (int) – The number of filters
  • filter_size (int) – The filter size
  • stride (int) – The stride step
  • dilation_rate (int) – Specifying the dilation rate to use for dilated convolution.
  • act (activation function) – The function that is applied to the layer activations
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • data_format (str) – Default is ‘NWC’ as it is a 1D CNN.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer or None) – The initializer for the bias vector. If None, skip biases.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • name (str) – A unique layer name
Returns:

A Conv1dLayer object.

Return type:

Layer

Examples

>>> x = tf.placeholder(tf.float32, (batch_size, width))
>>> y_ = tf.placeholder(tf.int64, shape=(batch_size,))
>>> n = InputLayer(x, name='in')
>>> n = ReshapeLayer(n, (-1, width, 1), name='rs')
>>> n = Conv1d(n, 64, 3, 1, act=tf.nn.relu, name='c1')
>>> n = MaxPool1d(n, 2, 2, padding='valid', name='m1')
>>> n = Conv1d(n, 128, 3, 1, act=tf.nn.relu, name='c2')
>>> n = MaxPool1d(n, 2, 2, padding='valid', name='m2')
>>> n = Conv1d(n, 128, 3, 1, act=tf.nn.relu, name='c3')
>>> n = MaxPool1d(n, 2, 2, padding='valid', name='m3')
>>> n = FlattenLayer(n, name='f')
>>> n = DenseLayer(n, 500, tf.nn.relu, name='d1')
>>> n = DenseLayer(n, 100, tf.nn.relu, name='d2')
>>> n = DenseLayer(n, 2, tf.identity, name='o')

2D Convolution

tensorlayer.layers.Conv2d(layer, n_filter=32, filter_size=(3, 3), strides=(1, 1), act=<function identity>, padding='SAME', W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, use_cudnn_on_gpu=None, data_format=None, name='conv2d')

Simplified version of Conv2dLayer.

Parameters:
  • layer (Layer) – Previous layer.
  • n_filter (int) – The number of filters.
  • filter_size (tuple of int) – The filter size (height, width).
  • strides (tuple of int) – The sliding window strides of corresponding input dimensions. It must be in the same order as the shape parameter.
  • act (activation function) – The activation function of this layer.
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • W_init (initializer) – The initializer for the the weight matrix.
  • b_init (initializer or None) – The initializer for the the bias vector. If None, skip biases.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • use_cudnn_on_gpu (bool) – Default is False.
  • data_format (str) – “NHWC” or “NCHW”, default is “NHWC”.
  • name (str) – A unique layer name.
Returns:

A Conv2dLayer object.

Return type:

Layer

Examples

>>> net = InputLayer(x, name='inputs')
>>> net = Conv2d(net, 64, (3, 3), act=tf.nn.relu, name='conv1_1')
>>> net = Conv2d(net, 64, (3, 3), act=tf.nn.relu, name='conv1_2')
>>> net = MaxPool2d(net, (2, 2), name='pool1')
>>> net = Conv2d(net, 128, (3, 3), act=tf.nn.relu, name='conv2_1')
>>> net = Conv2d(net, 128, (3, 3), act=tf.nn.relu, name='conv2_2')
>>> net = MaxPool2d(net, (2, 2), name='pool2')

2D Deconvolution

tensorlayer.layers.DeConv2d(layer, n_filter=32, filter_size=(3, 3), out_size=(30, 30), strides=(2, 2), padding='SAME', batch_size=None, act=<function identity>, W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, name='decnn2d')

Simplified version of DeConv2dLayer.

Parameters:
  • layer (Layer) – Previous layer.
  • n_filter (int) – The number of filters.
  • filter_size (tuple of int) – The filter size (height, width).
  • out_size (tuple of int) – Require if TF version < 1.3, (height, width) of output.
  • strides (tuple of int) – The stride step (height, width).
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • batch_size (int) – Require if TF version < 1.3, int or None. If None, try to find the batch_size from the first dim of net.outputs (you should define the batch_size in the input placeholder).
  • act (activation function) – The activation function of this layer.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer or None) – The initializer for the bias vector. If None, skip biases.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • name (str) – A unique layer name.
Returns:

A DeConv2dLayer object.

Return type:

Layer

3D Deconvolution

class tensorlayer.layers.DeConv3d(prev_layer, n_filter=32, filter_size=(3, 3, 3), strides=(2, 2, 2), padding='SAME', act=<function identity>, W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, name='decnn3d')[source]

Simplified version of The DeConv3dLayer, see tf.contrib.layers.conv3d_transpose.

Parameters:
  • layer (Layer) – Previous layer.
  • n_filter (int) – The number of filters.
  • filter_size (tuple of int) – The filter size (depth, height, width).
  • stride (tuple of int) – The stride step (depth, height, width).
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • act (activation function) – The activation function of this layer.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer or None) – The initializer for the bias vector. If None, skip bias.
  • name (str) – A unique layer name.

2D Depthwise/Separable Conv

class tensorlayer.layers.DepthwiseConv2d(prev_layer, channel_multiplier=1, shape=(3, 3), strides=(1, 1), act=<function identity>, padding='SAME', rate=(1, 1), W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, name='depthwise_conv2d')[source]

Separable/Depthwise Convolutional 2D layer, see tf.nn.depthwise_conv2d.

Input:
4-D Tensor (batch, height, width, in_channels).
Output:
4-D Tensor (batch, new height, new width, in_channels * channel_multiplier).
Parameters:
  • layer (Layer) – Previous layer.
  • channel_multiplier (int) – The number of channels to expand to.
  • filter_size (tuple of int) – The filter size (height, width).
  • stride (tuple of int) – The stride step (height, width).
  • act (activation function) – The activation function of this layer.
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • rate (tuple of 2 int) – The dilation rate in which we sample input values across the height and width dimensions in atrous convolution. If it is greater than 1, then all values of strides must be 1.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer or None) – The initializer for the bias vector. If None, skip bias.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder(tf.float32, shape=[None, 28, 28, 1], name='x')
>>> n = InputLayer(x, name='in')
>>> n = Conv2d(n, 32, (3, 3), (2, 2), act=tf.nn.relu, name='c1')
>>> n = DepthwiseConv2d(n, 1, (3, 3), (1, 1), name='d1')
>>> print(n.outputs.get_shape())
... (?, 14, 14, 32)

References

2D Deformable Conv

class tensorlayer.layers.DeformableConv2d(prev_layer, offset_layer=None, n_filter=32, filter_size=(3, 3), act=<function identity>, name='deformable_conv_2d', W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None)[source]

The DeformableConv2d class is a 2D Deformable Convolutional Networks.

Parameters:
  • layer (Layer) – Previous layer.
  • offset_layer (Layer) – To predict the offset of convolution operations. The output shape is (batchsize, input height, input width, 2*(number of element in the convolution kernel)) e.g. if apply a 3*3 kernel, the number of the last dimension should be 18 (2*3*3)
  • n_filter (int) – The number of filters.
  • filter_size (tuple of int) – The filter size (height, width).
  • act (activation function) – The activation function of this layer.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer or None) – The initializer for the bias vector. If None, skip biases.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • name (str) – A unique layer name.

Examples

>>> net = tl.layers.InputLayer(x, name='input_layer')
>>> offset1 = tl.layers.Conv2d(net, 18, (3, 3), (1, 1), act=act, padding='SAME', name='offset1')
>>> net = tl.layers.DeformableConv2d(net, offset1, 32, (3, 3), act=act, name='deformable1')
>>> offset2 = tl.layers.Conv2d(net, 18, (3, 3), (1, 1), act=act, padding='SAME', name='offset2')
>>> net = tl.layers.DeformableConv2d(net, offset2, 64, (3, 3), act=act, name='deformable2')

References

  • The deformation operation was adapted from the implementation in here

Notes

  • The padding is fixed to ‘SAME’.
  • The current implementation is not optimized for memory usgae. Please use it carefully.

2D Grouped Conv

class tensorlayer.layers.GroupConv2d(prev_layer=None, n_filter=32, filter_size=(3, 3), strides=(2, 2), n_group=2, act=<function identity>, padding='SAME', W_init=<tensorflow.python.ops.init_ops.TruncatedNormal object>, b_init=<tensorflow.python.ops.init_ops.Constant object>, W_init_args=None, b_init_args=None, name='groupconv')[source]

The GroupConv2d class is 2D grouped convolution, see here.

Parameters:
  • layer (Layer) – Previous layer.
  • n_filter (int) – The number of filters.
  • filter_size (int) – The filter size.
  • stride (int) – The stride step.
  • n_group (int) – The number of groups.
  • act (activation function) – The activation function of this layer.
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • W_init (initializer) – The initializer for the weight matrix.
  • b_init (initializer or None) – The initializer for the bias vector. If None, skip biases.
  • W_init_args (dictionary) – The arguments for the weight matrix initializer.
  • b_init_args (dictionary) – The arguments for the bias vector initializer.
  • name (str) – A unique layer name.

Super-Resolution layer

1D Subpixel Convolution

tensorlayer.layers.SubpixelConv1d(net, scale=2, act=<function identity>, name='subpixel_conv1d')

It is a 1D sub-pixel up-sampling layer.

Calls a TensorFlow function that directly implements this functionality. We assume input has dim (batch, width, r)

Parameters:
  • net (Layer) – Previous layer with output shape of (batch, width, r).
  • scale (int) – The up-scaling ratio, a wrong setting will lead to Dimension size error.
  • act (activation function) – The activation function of this layer.
  • name (str) – A unique layer name.
Returns:

A 1D sub-pixel up-sampling layer

Return type:

Layer

Examples

>>> t_signal = tf.placeholder('float32', [10, 100, 4], name='x')
>>> n = InputLayer(t_signal, name='in')
>>> n = SubpixelConv1d(n, scale=2, name='s')
>>> print(n.outputs.shape)
... (10, 200, 2)

References

Audio Super Resolution Implementation.

2D Subpixel Convolution

tensorlayer.layers.SubpixelConv2d(net, scale=2, n_out_channel=None, act=<function identity>, name='subpixel_conv2d')

It is a 2D sub-pixel up-sampling layer, usually be used for Super-Resolution applications, see SRGAN for example.

Parameters:
  • net (Layer) – Previous layer,
  • scale (int) – The up-scaling ratio, a wrong setting will lead to dimension size error.
  • n_out_channel (int or None) – The number of output channels. - If None, automatically set n_out_channel == the number of input channels / (scale x scale). - The number of input channels == (scale x scale) x The number of output channels.
  • act (activation function) – The activation function of this layer.
  • name (str) – A unique layer name.
Returns:

A 2D sub-pixel up-sampling layer

Return type:

Layer

Examples

>>> # examples here just want to tell you how to set the n_out_channel.
>>> x = np.random.rand(2, 16, 16, 4)
>>> X = tf.placeholder("float32", shape=(2, 16, 16, 4), name="X")
>>> net = InputLayer(X, name='input')
>>> net = SubpixelConv2d(net, scale=2, n_out_channel=1, name='subpixel_conv2d')
>>> y = sess.run(net.outputs, feed_dict={X: x})
>>> print(x.shape, y.shape)
... (2, 16, 16, 4) (2, 32, 32, 1)
>>>
>>> x = np.random.rand(2, 16, 16, 4*10)
>>> X = tf.placeholder("float32", shape=(2, 16, 16, 4*10), name="X")
>>> net = InputLayer(X, name='input2')
>>> net = SubpixelConv2d(net, scale=2, n_out_channel=10, name='subpixel_conv2d2')
>>> y = sess.run(net.outputs, feed_dict={X: x})
>>> print(x.shape, y.shape)
... (2, 16, 16, 40) (2, 32, 32, 10)
>>>
>>> x = np.random.rand(2, 16, 16, 25*10)
>>> X = tf.placeholder("float32", shape=(2, 16, 16, 25*10), name="X")
>>> net = InputLayer(X, name='input3')
>>> net = SubpixelConv2d(net, scale=5, n_out_channel=None, name='subpixel_conv2d3')
>>> y = sess.run(net.outputs, feed_dict={X: x})
>>> print(x.shape, y.shape)
... (2, 16, 16, 250) (2, 80, 80, 10)

References

Spatial Transformer

2D Affine Transformation

class tensorlayer.layers.SpatialTransformer2dAffineLayer(prev_layer=None, theta_layer=None, out_size=None, name='sapatial_trans_2d_affine')[source]

The SpatialTransformer2dAffineLayer class is a 2D Spatial Transformer Layer for 2D Affine Transformation.

Parameters:
  • layer (Layer) – Previous layer.
  • theta_layer (Layer) – The localisation network. - We will use a DenseLayer to make the theta size to [batch, 6], value range to [0, 1] (via tanh).
  • out_size (tuple of int or None) – The size of the output of the network (height, width), the feature maps will be resized by this.
  • name (str) – A unique layer name.

References

2D Affine Transformation function

tensorlayer.layers.transformer(U, theta, out_size, name='SpatialTransformer2dAffine')[source]

Spatial Transformer Layer for 2D Affine Transformation , see SpatialTransformer2dAffineLayer class.

Parameters:
  • U (list of float) – The output of a convolutional net should have the shape [num_batch, height, width, num_channels].
  • theta (float) – The output of the localisation network should be [num_batch, 6], value range should be [0, 1] (via tanh).
  • out_size (tuple of int) – The size of the output of the network (height, width)
  • name (str) – Optional function name
Returns:

The transformed tensor.

Return type:

Tensor

References

Notes

To initialize the network to the identity transform init.

>>> ``theta`` to
>>> identity = np.array([[1., 0., 0.],
...                      [0., 1., 0.]])
>>> identity = identity.flatten()
>>> theta = tf.Variable(initial_value=identity)

Batch 2D Affine Transformation function

tensorlayer.layers.batch_transformer(U, thetas, out_size, name='BatchSpatialTransformer2dAffine')[source]

Batch Spatial Transformer function for 2D Affine Transformation.

Parameters:
  • U (list of float) – tensor of inputs [batch, height, width, num_channels]
  • thetas (list of float) – a set of transformations for each input [batch, num_transforms, 6]
  • out_size (list of int) – the size of the output [out_height, out_width]
  • name (str) – optional function name
Returns:

Tensor of size [batch * num_transforms, out_height, out_width, num_channels]

Return type:

float

Pooling and Padding layers

Pooling (Pro)

Pooling layer for any dimensions and any pooling functions.

class tensorlayer.layers.PoolLayer(prev_layer=None, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1), padding='SAME', pool=<function max_pool>, name='pool_layer')[source]

The PoolLayer class is a Pooling layer. You can choose tf.nn.max_pool and tf.nn.avg_pool for 2D input or tf.nn.max_pool3d and tf.nn.avg_pool3d for 3D input.

Parameters:
  • layer (Layer) – The previous layer.
  • ksize (tuple of int) – The size of the window for each dimension of the input tensor. Note that: len(ksize) >= 4.
  • strides (tuple of int) – The stride of the sliding window for each dimension of the input tensor. Note that: len(strides) >= 4.
  • padding (str) – The padding algorithm type: “SAME” or “VALID”.
  • pool (pooling function) – One of tf.nn.max_pool, tf.nn.avg_pool, tf.nn.max_pool3d and f.nn.avg_pool3d. See TensorFlow pooling APIs
  • name (str) – A unique layer name.

Examples

Padding (Pro)

Padding layer for any modes.

class tensorlayer.layers.PadLayer(prev_layer, paddings, mode='CONSTANT', name='pad_layer')[source]

The PadLayer class is a padding layer for any mode and dimension. Please see tf.pad for usage.

Parameters:
  • layer (Layer) – The previous layer.
  • paddings (Tensor) – The int32 values to pad.
  • mode (str) – “CONSTANT”, “REFLECT”, or “SYMMETRIC” (case-insensitive).
  • name (str) – A unique layer name.

1D Max pooling

tensorlayer.layers.MaxPool1d(net, filter_size=3, strides=2, padding='valid', data_format='channels_last', name=None)

Wrapper for tf.layers.max_pooling1d .

Parameters:
  • net (Layer) – The previous layer with a output rank as 3.
  • filter_size (tuple of int) – Pooling window size.
  • strides (tuple of int) – Strides of the pooling operation.
  • padding (str) – The padding method: ‘valid’ or ‘same’.
  • data_format (str) – One of channels_last (default) or channels_first. The ordering of the dimensions must match the inputs. channels_last corresponds to inputs with the shape (batch, length, channels); while channels_first corresponds to inputs with shape (batch, channels, length).
  • name (str) – A unique layer name.
Returns:

A max pooling 1-D layer with a output rank as 3.

Return type:

Layer

1D Mean pooling

tensorlayer.layers.MeanPool1d(net, filter_size=3, strides=2, padding='valid', data_format='channels_last', name=None)

Wrapper for tf.layers.average_pooling1d .

Parameters:
  • net (Layer) – The previous layer with a output rank as 3.
  • filter_size (tuple of int) – Pooling window size.
  • strides (tuple of int) – Strides of the pooling operation.
  • padding (str) – The padding method: ‘valid’ or ‘same’.
  • data_format (str) – One of channels_last (default) or channels_first. The ordering of the dimensions must match the inputs. channels_last corresponds to inputs with the shape (batch, length, channels); while channels_first corresponds to inputs with shape (batch, channels, length).
  • name (str) – A unique layer name.
Returns:

A mean pooling 1-D layer with a output rank as 3.

Return type:

Layer

2D Max pooling

tensorlayer.layers.MaxPool2d(net, filter_size=(3, 3), strides=(2, 2), padding='SAME', name='maxpool')

Wrapper for PoolLayer.

Parameters:
  • net (Layer) – The previous layer with a output rank as 4.
  • filter_size (tuple of int) – (height, width) for filter size.
  • strides (tuple of int) – (height, width) for strides.
  • padding (str) – The padding method: ‘valid’ or ‘same’.
  • name (str) – A unique layer name.
Returns:

A max pooling 2-D layer with a output rank as 4.

Return type:

Layer

2D Mean pooling

tensorlayer.layers.MeanPool2d(net, filter_size=(3, 3), strides=(2, 2), padding='SAME', name='meanpool')

Wrapper for PoolLayer.

Parameters:
  • layer (Layer) – The previous layer with a output rank as 4.
  • filter_size (tuple of int) – (height, width) for filter size.
  • strides (tuple of int) – (height, width) for strides.
  • padding (str) – The padding method: ‘valid’ or ‘same’.
  • name (str) – A unique layer name.
Returns:

A mean pooling 2-D layer with a output rank as 4.

Return type:

Layer

3D Max pooling

class tensorlayer.layers.MaxPool3d(prev_layer, filter_size=(3, 3, 3), strides=(2, 2, 2), padding='valid', data_format='channels_last', name='maxpool3d')[source]

Wrapper for tf.layers.max_pooling3d .

Parameters:
  • layer (Layer) – The previous layer with a output rank as 5.
  • filter_size (tuple of int) – Pooling window size.
  • strides (tuple of int) – Strides of the pooling operation.
  • padding (str) – The padding method: ‘valid’ or ‘same’.
  • data_format (str) – One of channels_last (default) or channels_first. The ordering of the dimensions must match the inputs. channels_last corresponds to inputs with the shape (batch, length, channels); while channels_first corresponds to inputs with shape (batch, channels, length).
  • name (str) – A unique layer name.
Returns:

A max pooling 3-D layer with a output rank as 5.

Return type:

Layer

3D Mean pooling

class tensorlayer.layers.MeanPool3d(prev_layer, filter_size=(3, 3, 3), strides=(2, 2, 2), padding='valid', data_format='channels_last', name='meanpool3d')[source]

Wrapper for tf.layers.average_pooling3d

Parameters:
  • layer (Layer) – The previous layer with a output rank as 5.
  • filter_size (tuple of int) – Pooling window size.
  • strides (tuple of int) – Strides of the pooling operation.
  • padding (str) – The padding method: ‘valid’ or ‘same’.
  • data_format (str) – One of channels_last (default) or channels_first. The ordering of the dimensions must match the inputs. channels_last corresponds to inputs with the shape (batch, length, channels); while channels_first corresponds to inputs with shape (batch, channels, length).
  • name (str) – A unique layer name.
Returns:

A mean pooling 3-D layer with a output rank as 5.

Return type:

Layer

1D Global Max pooling

class tensorlayer.layers.GlobalMaxPool1d(prev_layer=None, name='globalmaxpool1d')[source]

The GlobalMaxPool1d class is a 1D Global Max Pooling layer.

Parameters:
  • layer (Layer) – The previous layer with a output rank as 3.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder("float32", [None, 100, 30])
>>> n = InputLayer(x, name='in')
>>> n = GlobalMaxPool1d(n)
... [None, 30]

1D Global Mean pooling

class tensorlayer.layers.GlobalMeanPool1d(prev_layer=None, name='globalmeanpool1d')[source]

The GlobalMeanPool1d class is a 1D Global Mean Pooling layer.

Parameters:
  • layer (Layer) – The previous layer with a output rank as 3.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder("float32", [None, 100, 30])
>>> n = InputLayer(x, name='in')
>>> n = GlobalMeanPool1d(n)
... [None, 30]

2D Global Max pooling

class tensorlayer.layers.GlobalMaxPool2d(prev_layer=None, name='globalmaxpool2d')[source]

The GlobalMaxPool2d class is a 2D Global Max Pooling layer.

Parameters:
  • layer (Layer) – The previous layer with a output rank as 4.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder("float32", [None, 100, 100, 30])
>>> n = InputLayer(x, name='in2')
>>> n = GlobalMaxPool2d(n)
... [None, 30]

2D Global Mean pooling

class tensorlayer.layers.GlobalMeanPool2d(prev_layer=None, name='globalmeanpool2d')[source]

The GlobalMeanPool2d class is a 2D Global Mean Pooling layer.

Parameters:
  • layer (Layer) – The previous layer with a output rank as 4.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder("float32", [None, 100, 100, 30])
>>> n = InputLayer(x, name='in2')
>>> n = GlobalMeanPool2d(n)
... [None, 30]

Normalization layer

For local response normalization as it does not have any weights and arguments, you can also apply tf.nn.lrn on network.outputs.

Batch Normalization

class tensorlayer.layers.BatchNormLayer(prev_layer, decay=0.9, epsilon=1e-05, act=<function identity>, is_train=False, beta_init=<class 'tensorflow.python.ops.init_ops.Zeros'>, gamma_init=<tensorflow.python.ops.init_ops.RandomNormal object>, name='batchnorm_layer')[source]

The BatchNormLayer is a batch normalization layer for both fully-connected and convolution outputs. See tf.nn.batch_normalization and tf.nn.moments.

Parameters:
  • layer (Layer) – The previous layer.
  • decay (float) – A decay factor for ExponentialMovingAverage. Suggest to use a large value for large dataset.
  • epsilon (float) – Eplison.
  • act (activation function) – The activation function of this layer.
  • is_train (boolean) – Is being used for training or inference.
  • beta_init (initializer) – The initializer for initializing beta.
  • gamma_init (initializer) – The initializer for initializing gamma.
  • dtype (TensorFlow dtype) – tf.float32 (default) or tf.float16.
  • name (str) – A unique layer name.

References

Local Response Normalization

class tensorlayer.layers.LocalResponseNormLayer(prev_layer, depth_radius=None, bias=None, alpha=None, beta=None, name='lrn_layer')[source]

The LocalResponseNormLayer layer is for Local Response Normalization. See tf.nn.local_response_normalization or tf.nn.lrn for new TF version. The 4-D input tensor is a 3-D array of 1-D vectors (along the last dimension), and each vector is normalized independently. Within a given vector, each component is divided by the weighted square-sum of inputs within depth_radius.

Parameters:
  • layer (Layer) – The previous layer with a 4D output shape.
  • depth_radius (int) – Depth radius. 0-D. Half-width of the 1-D normalization window.
  • bias (float) – An offset which is usually positive and shall avoid dividing by 0.
  • alpha (float) – A scale factor which is usually positive.
  • beta (float) – An exponent.
  • name (str) – A unique layer name.

Instance Normalization

class tensorlayer.layers.InstanceNormLayer(prev_layer, act=<function identity>, epsilon=1e-05, name='instan_norm')[source]

The InstanceNormLayer class is a for instance normalization.

Parameters:
  • layer (Layer) – The previous layer.
  • act (activation function.) – The activation function of this layer.
  • epsilon (float) – Eplison.
  • name (str) – A unique layer name

Layer Normalization

class tensorlayer.layers.LayerNormLayer(prev_layer, center=True, scale=True, act=<function identity>, reuse=None, variables_collections=None, outputs_collections=None, trainable=True, begin_norm_axis=1, begin_params_axis=-1, name='layernorm')[source]

The LayerNormLayer class is for layer normalization, see tf.contrib.layers.layer_norm.

Parameters:

Object Detection

ROI layer

class tensorlayer.layers.ROIPoolingLayer(prev_layer, rois, pool_height=2, pool_width=2, name='roipooling_layer')[source]

The region of interest pooling layer.

Parameters:
  • layer (Layer) – The previous layer.
  • rois (tuple of int) – Regions of interest in the format of (feature map index, upper left, bottom right).
  • pool_width (int) – The size of the pooling sections.
  • pool_width – The size of the pooling sections.
  • name (str) – A unique layer name.

Notes

  • This implementation is imported from Deepsense-AI .
  • Please install it by the instruction HERE.

Time distributed layer

class tensorlayer.layers.TimeDistributedLayer(prev_layer, layer_class=None, args=None, name='time_distributed')[source]

The TimeDistributedLayer class that applies a function to every timestep of the input tensor. For example, if use DenseLayer as the layer_class, we input (batch_size, length, dim) and output (batch_size , length, new_dim).

Parameters:
  • layer (Layer) – Previous layer with output size of (batch_size, length, dim).
  • layer_class (a Layer class) – The layer class name.
  • args (dictionary) – The arguments for the layer_class.
  • name (str) – A unique layer name.

Examples

>>> batch_size = 32
>>> timestep = 20
>>> input_dim = 100
>>> x = tf.placeholder(dtype=tf.float32, shape=[batch_size, timestep, input_dim], name="encode_seqs")
>>> net = InputLayer(x, name='input')
>>> net = TimeDistributedLayer(net, layer_class=DenseLayer, args={'n_units':50, 'name':'dense'}, name='time_dense')
... [TL] InputLayer  input: (32, 20, 100)
... [TL] TimeDistributedLayer time_dense: layer_class:DenseLayer
>>> print(net.outputs._shape)
... (32, 20, 50)
>>> net.print_params(False)
... param   0: (100, 50)          time_dense/dense/W:0
... param   1: (50,)              time_dense/dense/b:0
... num of params: 5050

Fixed Length Recurrent layer

All recurrent layers can implement any type of RNN cell by feeding different cell function (LSTM, GRU etc).

RNN layer

class tensorlayer.layers.RNNLayer(prev_layer, cell_fn, cell_init_args=None, n_hidden=100, initializer=<tensorflow.python.ops.init_ops.RandomUniform object>, n_steps=5, initial_state=None, return_last=False, return_seq_2d=False, name='rnn')[source]

The RNNLayer class is a fixed length recurrent layer for implementing vanilla RNN, LSTM, GRU and etc.

Parameters:
  • layer (Layer) – Previous layer.
  • cell_fn (TensorFlow cell function) –
    A TensorFlow core RNN cell
  • cell_init_args (dictionary) – The arguments for the cell function.
  • n_hidden (int) – The number of hidden units in the layer.
  • initializer (initializer) – The initializer for initializing the model parameters.
  • n_steps (int) – The fixed sequence length.
  • initial_state (None or RNN State) – If None, initial_state is zero state.
  • return_last (boolean) –
    Whether return last output or all outputs in each step.
    • If True, return the last output, “Sequence input and single output”
    • If False, return all outputs, “Synced sequence input and output”
    • In other word, if you want to stack more RNNs on this layer, set to False.
  • return_seq_2d (boolean) –
    Only consider this argument when return_last is False
    • If True, return 2D Tensor [n_example, n_hidden], for stacking DenseLayer after it.
    • If False, return 3D Tensor [n_example/n_steps, n_steps, n_hidden], for stacking multiple RNN after it.
  • name (str) – A unique layer name.
outputs

Tensor – The output of this layer.

final_state

Tensor or StateTuple

The finial state of this layer.
  • When state_is_tuple is False, it is the final hidden and cell states, states.get_shape() = [?, 2 * n_hidden].
  • When state_is_tuple is True, it stores two elements: (c, h).
  • In practice, you can get the final state after each iteration during training, then feed it to the initial state of next iteration.
initial_state

Tensor or StateTuple

The initial state of this layer.
  • In practice, you can set your state at the begining of each epoch or iteration according to your training procedure.
batch_size

int or Tensor – It is an integer, if it is able to compute the batch_size; otherwise, tensor for dynamic batch size.

Examples

  • For synced sequence input and output, see PTB example
  • For encoding see below.
>>> batch_size = 32
>>> num_steps = 5
>>> vocab_size = 3000
>>> hidden_size = 256
>>> keep_prob = 0.8
>>> is_train = True
>>> input_data = tf.placeholder(tf.int32, [batch_size, num_steps])
>>> net = tl.layers.EmbeddingInputlayer(inputs=input_data, vocabulary_size=vocab_size,
...     embedding_size=hidden_size, name='embed')
>>> net = tl.layers.DropoutLayer(net, keep=keep_prob, is_fix=True, is_train=is_train, name='drop1')
>>> net = tl.layers.RNNLayer(net, cell_fn=tf.contrib.rnn.BasicLSTMCell,
...     n_hidden=hidden_size, n_steps=num_steps, return_last=False, name='lstm1')
>>> net = tl.layers.DropoutLayer(net, keep=keep_prob, is_fix=True, is_train=is_train, name='drop2')
>>> net = tl.layers.RNNLayer(net, cell_fn=tf.contrib.rnn.BasicLSTMCell,
...     n_hidden=hidden_size, n_steps=num_steps, return_last=True, name='lstm2')
>>> net = tl.layers.DropoutLayer(net, keep=keep_prob, is_fix=True, is_train=is_train, name='drop3')
>>> net = tl.layers.DenseLayer(net, n_units=vocab_size, name='output')
  • For CNN+LSTM
>>> image_size = 100
>>> batch_size = 10
>>> num_steps = 5
>>> x = tf.placeholder(tf.float32, shape=[batch_size, image_size, image_size, 1])
>>> net = tl.layers.InputLayer(x, name='in')
>>> net = tl.layers.Conv2d(net, 32, (5, 5), (2, 2), tf.nn.relu, name='cnn1')
>>> net = tl.layers.MaxPool2d(net, (2, 2), (2, 2), name='pool1')
>>> net = tl.layers.Conv2d(net, 10, (5, 5), (2, 2), tf.nn.relu, name='cnn2')
>>> net = tl.layers.MaxPool2d(net, (2, 2), (2, 2), name='pool2')
>>> net = tl.layers.FlattenLayer(net, name='flatten')
>>> net = tl.layers.ReshapeLayer(net, shape=[-1, num_steps, int(net.outputs._shape[-1])])
>>> rnn = tl.layers.RNNLayer(net, cell_fn=tf.contrib.rnn.BasicLSTMCell, n_hidden=200, n_steps=num_steps, return_last=False, return_seq_2d=True, name='rnn')
>>> net = tl.layers.DenseLayer(rnn, 3, name='out')

Notes

Input dimension should be rank 3 : [batch_size, n_steps, n_features], if no, please see ReshapeLayer.

References

Bidirectional layer

class tensorlayer.layers.BiRNNLayer(prev_layer, cell_fn, cell_init_args=None, n_hidden=100, initializer=<tensorflow.python.ops.init_ops.RandomUniform object>, n_steps=5, fw_initial_state=None, bw_initial_state=None, dropout=None, n_layer=1, return_last=False, return_seq_2d=False, name='birnn')[source]

The BiRNNLayer class is a fixed length Bidirectional recurrent layer.

Parameters:
  • layer (Layer) – Previous layer.
  • cell_fn (TensorFlow cell function) –
    A TensorFlow core RNN cell.
  • cell_init_args (dictionary or None) – The arguments for the cell function.
  • n_hidden (int) – The number of hidden units in the layer.
  • initializer (initializer) – The initializer for initializing the model parameters.
  • n_steps (int) – The fixed sequence length.
  • fw_initial_state (None or forward RNN State) – If None, initial_state is zero state.
  • bw_initial_state (None or backward RNN State) – If None, initial_state is zero state.
  • dropout (tuple of float or int) – The input and output keep probability (input_keep_prob, output_keep_prob). If one int, input and output keep probability are the same.
  • n_layer (int) – The number of RNN layers, default is 1.
  • return_last (boolean) –
    Whether return last output or all outputs in each step.
    • If True, return the last output, “Sequence input and single output”
    • If False, return all outputs, “Synced sequence input and output”
    • In other word, if you want to stack more RNNs on this layer, set to False.
  • return_seq_2d (boolean) –
    Only consider this argument when return_last is False
    • If True, return 2D Tensor [n_example, n_hidden], for stacking DenseLayer after it.
    • If False, return 3D Tensor [n_example/n_steps, n_steps, n_hidden], for stacking multiple RNN after it.
  • name (str) – A unique layer name.
outputs

tensor – The output of this layer.

fw(bw)_final_state

tensor or StateTuple

The finial state of this layer.
  • When state_is_tuple is False, it is the final hidden and cell states, states.get_shape() = [?, 2 * n_hidden].
  • When state_is_tuple is True, it stores two elements: (c, h).
  • In practice, you can get the final state after each iteration during training, then feed it to the initial state of next iteration.
fw(bw)_initial_state

tensor or StateTuple

The initial state of this layer.
  • In practice, you can set your state at the begining of each epoch or iteration according to your training procedure.
batch_size

int or tensor – It is an integer, if it is able to compute the batch_size; otherwise, tensor for dynamic batch size.

Notes

Input dimension should be rank 3 : [batch_size, n_steps, n_features]. If not, please see ReshapeLayer. For predicting, the sequence length has to be the same with the sequence length of training, while, for normal RNN, we can use sequence length of 1 for predicting.

References

Source

Recurrent Convolutional layer

Conv RNN Cell

class tensorlayer.layers.ConvRNNCell[source]

Abstract object representing an Convolutional RNN Cell.

Basic Conv LSTM Cell

class tensorlayer.layers.BasicConvLSTMCell(shape, filter_size, num_features, forget_bias=1.0, input_size=None, state_is_tuple=False, act=<function tanh>)[source]

Basic Conv LSTM recurrent network cell.

Parameters:
  • shape (tuple of int) – The height and width of the cell.
  • filter_size (tuple of int) – The height and width of the filter
  • num_features (int) – The hidden size of the cell
  • forget_bias (float) – The bias added to forget gates (see above).
  • input_size (int) – Deprecated and unused.
  • state_is_tuple (boolen) – If True, accepted and returned states are 2-tuples of the c_state and m_state. If False, they are concatenated along the column axis. The latter behavior will soon be deprecated.
  • act (activation function) – The activation function of this layer, tanh as default.

Conv LSTM layer

class tensorlayer.layers.ConvLSTMLayer(prev_layer, cell_shape=None, feature_map=1, filter_size=(3, 3), cell_fn=<class 'tensorlayer.layers.recurrent.BasicConvLSTMCell'>, initializer=<tensorflow.python.ops.init_ops.RandomUniform object>, n_steps=5, initial_state=None, return_last=False, return_seq_2d=False, name='convlstm')[source]

A fixed length Convolutional LSTM layer.

See this paper .

Parameters:
  • layer (Layer) – Previous layer
  • cell_shape (tuple of int) – The shape of each cell width * height
  • filter_size (tuple of int) – The size of filter width * height
  • cell_fn (a convolutional RNN cell) – Cell function like BasicConvLSTMCell
  • feature_map (int) – The number of feature map in the layer.
  • initializer (initializer) – The initializer for initializing the parameters.
  • n_steps (int) – The sequence length.
  • initial_state (None or ConvLSTM State) – If None, initial_state is zero state.
  • return_last (boolean) –
    Whether return last output or all outputs in each step.
    • If True, return the last output, “Sequence input and single output”.
    • If False, return all outputs, “Synced sequence input and output”.
    • In other word, if you want to stack more RNNs on this layer, set to False.
  • return_seq_2d (boolean) –
    Only consider this argument when return_last is False
    • If True, return 2D Tensor [n_example, n_hidden], for stacking DenseLayer after it.
    • If False, return 3D Tensor [n_example/n_steps, n_steps, n_hidden], for stacking multiple RNN after it.
  • name (str) – A unique layer name.
outputs

tensor – The output of this RNN. return_last = False, outputs = all cell_output, which is the hidden state. cell_output.get_shape() = (?, h, w, c])

final_state

tensor or StateTuple

The finial state of this layer.
  • When state_is_tuple = False, it is the final hidden and cell states,
  • When state_is_tuple = True, You can get the final state after each iteration during training, then feed it to the initial state of next iteration.
initial_state

tensor or StateTuple – It is the initial state of this ConvLSTM layer, you can use it to initialize your state at the beginning of each epoch or iteration according to your training procedure.

batch_size

int or tensor – Is int, if able to compute the batch_size, otherwise, tensor for ?.

Advanced Ops for Dynamic RNN

These operations usually be used inside Dynamic RNN layer, they can compute the sequence lengths for different situation and get the last RNN outputs by indexing.

Output indexing

tensorlayer.layers.advanced_indexing_op(inputs, index)[source]

Advanced Indexing for Sequences, returns the outputs by given sequence lengths. When return the last output DynamicRNNLayer uses it to get the last outputs with the sequence lengths.

Parameters:
  • inputs (tensor for data) – With shape of [batch_size, n_step(max), n_features]
  • index (tensor for indexing) – Sequence length in Dynamic RNN. [batch_size]

Examples

>>> batch_size, max_length, n_features = 3, 5, 2
>>> z = np.random.uniform(low=-1, high=1, size=[batch_size, max_length, n_features]).astype(np.float32)
>>> b_z = tf.constant(z)
>>> sl = tf.placeholder(dtype=tf.int32, shape=[batch_size])
>>> o = advanced_indexing_op(b_z, sl)
>>>
>>> sess = tf.InteractiveSession()
>>> tl.layers.initialize_global_variables(sess)
>>>
>>> order = np.asarray([1,1,2])
>>> print("real",z[0][order[0]-1], z[1][order[1]-1], z[2][order[2]-1])
>>> y = sess.run([o], feed_dict={sl:order})
>>> print("given",order)
>>> print("out", y)
... real [-0.93021595  0.53820813] [-0.92548317 -0.77135968] [ 0.89952248  0.19149846]
... given [1 1 2]
... out [array([[-0.93021595,  0.53820813],
...             [-0.92548317, -0.77135968],
...             [ 0.89952248,  0.19149846]], dtype=float32)]

References

  • Modified from TFlearn (the original code is used for fixed length rnn), references.

Compute Sequence length 1

tensorlayer.layers.retrieve_seq_length_op(data)[source]

An op to compute the length of a sequence from input shape of [batch_size, n_step(max), n_features], it can be used when the features of padding (on right hand side) are all zeros.

Parameters:data (tensor) – [batch_size, n_step(max), n_features] with zero padding on right hand side.

Examples

>>> data = [[[1],[2],[0],[0],[0]],
...         [[1],[2],[3],[0],[0]],
...         [[1],[2],[6],[1],[0]]]
>>> data = np.asarray(data)
>>> print(data.shape)
... (3, 5, 1)
>>> data = tf.constant(data)
>>> sl = retrieve_seq_length_op(data)
>>> sess = tf.InteractiveSession()
>>> tl.layers.initialize_global_variables(sess)
>>> y = sl.eval()
... [2 3 4]

Multiple features >>> data = [[[1,2],[2,2],[1,2],[1,2],[0,0]], … [[2,3],[2,4],[3,2],[0,0],[0,0]], … [[3,3],[2,2],[5,3],[1,2],[0,0]]] >>> print(sl) … [4 3 4]

References

Borrow from TFlearn.

Compute Sequence length 2

tensorlayer.layers.retrieve_seq_length_op2(data)[source]

An op to compute the length of a sequence, from input shape of [batch_size, n_step(max)], it can be used when the features of padding (on right hand side) are all zeros.

Parameters:data (tensor) – [batch_size, n_step(max)] with zero padding on right hand side.

Examples

>>> data = [[1,2,0,0,0],
...         [1,2,3,0,0],
...         [1,2,6,1,0]]
>>> o = retrieve_seq_length_op2(data)
>>> sess = tf.InteractiveSession()
>>> tl.layers.initialize_global_variables(sess)
>>> print(o.eval())
... [2 3 4]

Compute Sequence length 3

tensorlayer.layers.retrieve_seq_length_op3(data, pad_val=0)[source]

Return tensor for sequence length, if input is tf.string.

Get Mask

tensorlayer.layers.target_mask_op(data, pad_val=0)[source]

Return tensor for mask, if input is tf.string.

Dynamic RNN layer

RNN layer

class tensorlayer.layers.DynamicRNNLayer(prev_layer, cell_fn, cell_init_args=None, n_hidden=256, initializer=<tensorflow.python.ops.init_ops.RandomUniform object>, sequence_length=None, initial_state=None, dropout=None, n_layer=1, return_last=None, return_seq_2d=False, dynamic_rnn_init_args=None, name='dyrnn')[source]

The DynamicRNNLayer class is a dynamic recurrent layer, see tf.nn.dynamic_rnn.

Parameters:
  • layer (Layer) – Previous layer
  • cell_fn (TensorFlow cell function) –
    A TensorFlow core RNN cell
  • cell_init_args (dictionary or None) – The arguments for the cell function.
  • n_hidden (int) – The number of hidden units in the layer.
  • initializer (initializer) – The initializer for initializing the parameters.
  • sequence_length (tensor, array or None) –
    The sequence length of each row of input data, see Advanced Ops for Dynamic RNN.
    • If None, it uses retrieve_seq_length_op to compute the sequence length, i.e. when the features of padding (on right hand side) are all zeros.
    • If using word embedding, you may need to compute the sequence length from the ID array (the integer features before word embedding) by using retrieve_seq_length_op2 or retrieve_seq_length_op.
    • You can also input an numpy array.
    • More details about TensorFlow dynamic RNN in Wild-ML Blog.
  • initial_state (None or RNN State) – If None, initial_state is zero state.
  • dropout (tuple of float or int) –
    The input and output keep probability (input_keep_prob, output_keep_prob).
    • If one int, input and output keep probability are the same.
  • n_layer (int) – The number of RNN layers, default is 1.
  • return_last (boolean or None) –
    Whether return last output or all outputs in each step.
    • If True, return the last output, “Sequence input and single output”
    • If False, return all outputs, “Synced sequence input and output”
    • In other word, if you want to stack more RNNs on this layer, set to False.
  • return_seq_2d (boolean) –
    Only consider this argument when return_last is False
    • If True, return 2D Tensor [n_example, n_hidden], for stacking DenseLayer after it.
    • If False, return 3D Tensor [n_example/n_steps, n_steps, n_hidden], for stacking multiple RNN after it.
  • dynamic_rnn_init_args (dictionary) – The arguments for tf.nn.dynamic_rnn.
  • name (str) – A unique layer name.
outputs

tensor – The output of this layer.

final_state

tensor or StateTuple

The finial state of this layer.
  • When state_is_tuple is False, it is the final hidden and cell states, states.get_shape() = [?, 2 * n_hidden].
  • When state_is_tuple is True, it stores two elements: (c, h).
  • In practice, you can get the final state after each iteration during training, then feed it to the initial state of next iteration.
initial_state

tensor or StateTuple

The initial state of this layer.
  • In practice, you can set your state at the begining of each epoch or iteration according to your training procedure.
batch_size

int or tensor – It is an integer, if it is able to compute the batch_size; otherwise, tensor for dynamic batch size.

sequence_length

a tensor or array – The sequence lengths computed by Advanced Opt or the given sequence lengths, [batch_size]

Notes

Input dimension should be rank 3 : [batch_size, n_steps(max), n_features], if no, please see ReshapeLayer.

Examples

Synced sequence input and output, for loss function see tl.cost.cross_entropy_seq_with_mask.

>>> input_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name="input")
>>> net = tl.layers.EmbeddingInputlayer(
...             inputs=input_seqs,
...             vocabulary_size=vocab_size,
...             embedding_size=embedding_size,
...             name='embedding')
>>> net = tl.layers.DynamicRNNLayer(net,
...             cell_fn=tf.contrib.rnn.BasicLSTMCell, # for TF0.2 use tf.nn.rnn_cell.BasicLSTMCell,
...             n_hidden=embedding_size,
...             dropout=(0.7 if is_train else None),
...             sequence_length=tl.layers.retrieve_seq_length_op2(input_seqs),
...             return_last=False,                    # for encoder, set to True
...             return_seq_2d=True,                   # stack denselayer or compute cost after it
...             name='dynamicrnn')
... net = tl.layers.DenseLayer(net, n_units=vocab_size, name="output")

References

Bidirectional layer

class tensorlayer.layers.BiDynamicRNNLayer(prev_layer, cell_fn, cell_init_args=None, n_hidden=256, initializer=<tensorflow.python.ops.init_ops.RandomUniform object>, sequence_length=None, fw_initial_state=None, bw_initial_state=None, dropout=None, n_layer=1, return_last=False, return_seq_2d=False, dynamic_rnn_init_args=None, name='bi_dyrnn_layer')[source]

The BiDynamicRNNLayer class is a RNN layer, you can implement vanilla RNN, LSTM and GRU with it.

Parameters:
  • layer (Layer) – Previous layer.
  • cell_fn (TensorFlow cell function) –
    A TensorFlow core RNN cell
  • cell_init_args (dictionary) – The arguments for the cell initializer.
  • n_hidden (int) – The number of hidden units in the layer.
  • initializer (initializer) – The initializer for initializing the parameters.
  • sequence_length (tensor, array or None) –
    The sequence length of each row of input data, see Advanced Ops for Dynamic RNN.
    • If None, it uses retrieve_seq_length_op to compute the sequence length, i.e. when the features of padding (on right hand side) are all zeros.
    • If using word embedding, you may need to compute the sequence length from the ID array (the integer features before word embedding) by using retrieve_seq_length_op2 or retrieve_seq_length_op.
    • You can also input an numpy array.
    • More details about TensorFlow dynamic RNN in Wild-ML Blog.
  • fw_initial_state (None or forward RNN State) – If None, initial_state is zero state.
  • bw_initial_state (None or backward RNN State) – If None, initial_state is zero state.
  • dropout (tuple of float or int) –
    The input and output keep probability (input_keep_prob, output_keep_prob).
    • If one int, input and output keep probability are the same.
  • n_layer (int) – The number of RNN layers, default is 1.
  • return_last (boolean) –
    Whether return last output or all outputs in each step.
    • If True, return the last output, “Sequence input and single output”
    • If False, return all outputs, “Synced sequence input and output”
    • In other word, if you want to stack more RNNs on this layer, set to False.
  • return_seq_2d (boolean) –
    Only consider this argument when return_last is False
    • If True, return 2D Tensor [n_example, 2 * n_hidden], for stacking DenseLayer after it.
    • If False, return 3D Tensor [n_example/n_steps, n_steps, 2 * n_hidden], for stacking multiple RNN after it.
  • dynamic_rnn_init_args (dictionary) – The arguments for tf.nn.bidirectional_dynamic_rnn.
  • name (str) – A unique layer name.
outputs

tensor – The output of this layer. (?, 2 * n_hidden)

fw(bw)_final_state

tensor or StateTuple

The finial state of this layer.
  • When state_is_tuple is False, it is the final hidden and cell states, states.get_shape() = [?, 2 * n_hidden].
  • When state_is_tuple is True, it stores two elements: (c, h).
  • In practice, you can get the final state after each iteration during training, then feed it to the initial state of next iteration.
fw(bw)_initial_state

tensor or StateTuple

The initial state of this layer.
  • In practice, you can set your state at the begining of each epoch or iteration according to your training procedure.
batch_size

int or tensor – It is an integer, if it is able to compute the batch_size; otherwise, tensor for dynamic batch size.

sequence_length

a tensor or array – The sequence lengths computed by Advanced Opt or the given sequence lengths, [batch_size].

Notes

Input dimension should be rank 3 : [batch_size, n_steps(max), n_features], if no, please see ReshapeLayer.

References

Sequence to Sequence

Simple Seq2Seq

class tensorlayer.layers.Seq2Seq(net_encode_in, net_decode_in, cell_fn, cell_init_args=None, n_hidden=256, initializer=<tensorflow.python.ops.init_ops.RandomUniform object>, encode_sequence_length=None, decode_sequence_length=None, initial_state_encode=None, initial_state_decode=None, dropout=None, n_layer=1, return_seq_2d=False, name='seq2seq')[source]

The Seq2Seq class is a simple DynamicRNNLayer based Seq2seq layer without using tl.contrib.seq2seq. See Model and Sequence to Sequence Learning with Neural Networks.

Parameters:
  • net_encode_in (Layer) – Encode sequences, [batch_size, None, n_features].
  • net_decode_in (Layer) – Decode sequences, [batch_size, None, n_features].
  • cell_fn (TensorFlow cell function) –
    A TensorFlow core RNN cell
  • cell_init_args (dictionary or None) – The arguments for the cell initializer.
  • n_hidden (int) – The number of hidden units in the layer.
  • initializer (initializer) – The initializer for the parameters.
  • encode_sequence_length (tensor) – For encoder sequence length, see DynamicRNNLayer .
  • decode_sequence_length (tensor) – For decoder sequence length, see DynamicRNNLayer .
  • initial_state_encode (None or RNN state) – If None, initial_state_encode is zero state, it can be set by placeholder or other RNN.
  • initial_state_decode (None or RNN state) – If None, initial_state_decode is the final state of the RNN encoder, it can be set by placeholder or other RNN.
  • dropout (tuple of float or int) –
    The input and output keep probability (input_keep_prob, output_keep_prob).
    • If one int, input and output keep probability are the same.
  • n_layer (int) – The number of RNN layers, default is 1.
  • return_seq_2d (boolean) –
    Only consider this argument when return_last is False
    • If True, return 2D Tensor [n_example, 2 * n_hidden], for stacking DenseLayer after it.
    • If False, return 3D Tensor [n_example/n_steps, n_steps, 2 * n_hidden], for stacking multiple RNN after it.
  • name (str) – A unique layer name.
outputs

tensor – The output of RNN decoder.

initial_state_encode

tensor or StateTuple – Initial state of RNN encoder.

initial_state_decode

tensor or StateTuple – Initial state of RNN decoder.

final_state_encode

tensor or StateTuple – Final state of RNN encoder.

final_state_decode

tensor or StateTuple – Final state of RNN decoder.

Notes

  • How to feed data: Sequence to Sequence Learning with Neural Networks
  • input_seqs : ['how', 'are', 'you', '<PAD_ID>']
  • decode_seqs : ['<START_ID>', 'I', 'am', 'fine', '<PAD_ID>']
  • target_seqs : ['I', 'am', 'fine', '<END_ID>', '<PAD_ID>']
  • target_mask : [1, 1, 1, 1, 0]
  • related functions : tl.prepro <pad_sequences, precess_sequences, sequences_add_start_id, sequences_get_mask>

Examples

>>> from tensorlayer.layers import *
>>> batch_size = 32
>>> encode_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name="encode_seqs")
>>> decode_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name="decode_seqs")
>>> target_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name="target_seqs")
>>> target_mask = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name="target_mask") # tl.prepro.sequences_get_mask()
>>> with tf.variable_scope("model"):
...     # for chatbot, you can use the same embedding layer,
...     # for translation, you may want to use 2 seperated embedding layers
>>>     with tf.variable_scope("embedding") as vs:
>>>         net_encode = EmbeddingInputlayer(
...                 inputs = encode_seqs,
...                 vocabulary_size = 10000,
...                 embedding_size = 200,
...                 name = 'seq_embedding')
>>>         vs.reuse_variables()
>>>         tl.layers.set_name_reuse(True)
>>>         net_decode = EmbeddingInputlayer(
...                 inputs = decode_seqs,
...                 vocabulary_size = 10000,
...                 embedding_size = 200,
...                 name = 'seq_embedding')
>>>     net = Seq2Seq(net_encode, net_decode,
...             cell_fn = tf.contrib.rnn.BasicLSTMCell,
...             n_hidden = 200,
...             initializer = tf.random_uniform_initializer(-0.1, 0.1),
...             encode_sequence_length = retrieve_seq_length_op2(encode_seqs),
...             decode_sequence_length = retrieve_seq_length_op2(decode_seqs),
...             initial_state_encode = None,
...             dropout = None,
...             n_layer = 1,
...             return_seq_2d = True,
...             name = 'seq2seq')
>>> net_out = DenseLayer(net, n_units=10000, act=tf.identity, name='output')
>>> e_loss = tl.cost.cross_entropy_seq_with_mask(logits=net_out.outputs, target_seqs=target_seqs, input_mask=target_mask, return_details=False, name='cost')
>>> y = tf.nn.softmax(net_out.outputs)
>>> net_out.print_params(False)

Shape layer

Flatten layer

class tensorlayer.layers.FlattenLayer(prev_layer, name='flatten_layer')[source]

A layer that reshapes high-dimension input into a vector.

Then we often apply DenseLayer, RNNLayer, ConcatLayer and etc on the top of a flatten layer. [batch_size, mask_row, mask_col, n_mask] —> [batch_size, mask_row * mask_col * n_mask]

Parameters:
  • layer (Layer) – Previous layer.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder(tf.float32, shape=[None, 28, 28, 1])
>>> net = tl.layers.InputLayer(x, name='input')
>>> net = tl.layers.FlattenLayer(net, name='flatten')
... [?, 784]

Reshape layer

class tensorlayer.layers.ReshapeLayer(prev_layer, shape, name='reshape_layer')[source]

A layer that reshapes a given tensor.

Parameters:
  • layer (Layer) – Previous layer
  • shape (tuple of int) – The output shape, see tf.reshape.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder(tf.float32, shape=(None, 784))
>>> net = tl.layers.InputLayer(x, name='input')
>>> net = tl.layers.ReshapeLayer(net, [-1, 28, 28, 1], name='reshape')
>>> print(net.outputs)
... (?, 28, 28, 1)

Transpose layer

class tensorlayer.layers.TransposeLayer(prev_layer, perm, name='transpose')[source]

A layer that transposes the dimension of a tensor.

See tf.transpose() .

Parameters:
  • layer (Layer) – Previous layer
  • perm (list of int) – The permutation of the dimensions, similar with numpy.transpose.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder(tf.float32, shape=[None, 28, 28, 1])
>>> net = tl.layers.InputLayer(x, name='input')
>>> net = tl.layers.TransposeLayer(net, perm=[0, 1, 3, 2], name='trans')
... [None, 28, 1, 28]

Lambda layer

class tensorlayer.layers.LambdaLayer(prev_layer, fn, fn_args=None, name='lambda_layer')[source]

A layer that takes a user-defined function using TensorFlow Lambda.

Parameters:
  • layer (Layer) – Previous layer.
  • fn (function) – The function that applies to the outputs of previous layer.
  • fn_args (dictionary or None) – The arguments for the function (option).
  • name (str) – A unique layer name.

Examples

Non-parametric case

>>> x = tf.placeholder(tf.float32, shape=[None, 1], name='x')
>>> net = tl.layers.InputLayer(x, name='input')
>>> net = LambdaLayer(net, lambda x: 2*x, name='lambda')

Parametric case, merge other wrappers into TensorLayer

>>> from keras.layers import *
>>> from tensorlayer.layers import *
>>> def keras_block(x):
>>>     x = Dropout(0.8)(x)
>>>     x = Dense(800, activation='relu')(x)
>>>     x = Dropout(0.5)(x)
>>>     x = Dense(800, activation='relu')(x)
>>>     x = Dropout(0.5)(x)
>>>     logits = Dense(10, activation='linear')(x)
>>>     return logits
>>> net = InputLayer(x, name='input')
>>> net = LambdaLayer(net, fn=keras_block, name='keras')

Merge layer

Concat layer

class tensorlayer.layers.ConcatLayer(layers, concat_dim=1, name='concat_layer')[source]

A layer that concats multiple tensors according to given axis..

Parameters:
  • layers (list of Layer) – List of layers to concatenate.
  • concat_dim (int) – The dimension to concatenate.
  • name (str) – A unique layer name.

Examples

>>> sess = tf.InteractiveSession()
>>> x = tf.placeholder(tf.float32, shape=[None, 784])
>>> inputs = tl.layers.InputLayer(x, name='input_layer')
>>> net1 = tl.layers.DenseLayer(inputs, 800, act=tf.nn.relu, name='relu1_1')
>>> net2 = tl.layers.DenseLayer(inputs, 300, act=tf.nn.relu, name='relu2_1')
>>> net = tl.layers.ConcatLayer([net1, net2], 1, name ='concat_layer')
...   InputLayer input_layer (?, 784)
...   DenseLayer relu1_1: 800, relu
...   DenseLayer relu2_1: 300, relu
...   ConcatLayer concat_layer, 1100
>>> tl.layers.initialize_global_variables(sess)
>>> net.print_params()
... [TL]   param   0: relu1_1/W:0          (784, 800)         float32_ref
... [TL]   param   1: relu1_1/b:0          (800,)             float32_ref
... [TL]   param   2: relu2_1/W:0          (784, 300)         float32_ref
... [TL]   param   3: relu2_1/b:0          (300,)             float32_ref
...     num of params: 863500
>>> net.print_layers()
... [TL]   layer   0: relu1_1/Relu:0       (?, 800)           float32
... [TL]   layer   1: relu2_1/Relu:0       (?, 300)           float32
... [TL]   layer   2: concat_layer:0       (?, 1100)          float32

Element-wise layer

class tensorlayer.layers.ElementwiseLayer(layers, combine_fn=<function minimum>, act=None, name='elementwise_layer')[source]

A layer that combines multiple Layer that have the same output shapes according to an element-wise operation.

Parameters:
  • layers (list of Layer) – The list of layers to combine.
  • combine_fn (a TensorFlow element-wise combine function) – e.g. AND is tf.minimum ; OR is tf.maximum ; ADD is tf.add ; MUL is tf.multiply and so on. See TensorFlow Math API .
  • act (activation function) – The activation function of this layer.
  • name (str) – A unique layer name.

Examples

>>> net_0 = tl.layers.DenseLayer(inputs, n_units=500, act=tf.nn.relu, name='net_0')
>>> net_1 = tl.layers.DenseLayer(inputs, n_units=500, act=tf.nn.relu, name='net_1')
>>> net = tl.layers.ElementwiseLayer([net_0, net_1], combine_fn=tf.minimum, name='minimum')
>>> net.print_params(False)
... [TL]   param   0: net_0/W:0            (784, 500)         float32_ref
... [TL]   param   1: net_0/b:0            (500,)             float32_ref
... [TL]   param   2: net_1/W:0            (784, 500)         float32_ref
... [TL]   param   3: net_1/b:0            (500,)             float32_ref
>>> net.print_layers()
... [TL]   layer   0: net_0/Relu:0         (?, 500)           float32
... [TL]   layer   1: net_1/Relu:0         (?, 500)           float32
... [TL]   layer   2: minimum:0            (?, 500)           float32

Extend layer

Expand dims layer

class tensorlayer.layers.ExpandDimsLayer(prev_layer, axis, name='expand_dims')[source]

The ExpandDimsLayer class inserts a dimension of 1 into a tensor’s shape, see tf.expand_dims() .

Parameters:
  • layer (Layer) – The previous layer.
  • axis (int) – The dimension index at which to expand the shape of input.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder(tf.float32, (None, 100))
>>> n = tl.layers.InputLayer(x, name='in')
>>> n = tl.layers.ExpandDimsLayer(n, 2)
... [None, 100, 1]

Tile layer

class tensorlayer.layers.TileLayer(prev_layer=None, multiples=None, name='tile')[source]

The TileLayer class constructs a tensor by tiling a given tensor, see tf.tile() .

Parameters:
  • layer (Layer) – The previous layer.
  • multiples (tensor) – Must be one of the following types: int32, int64. 1-D Length must be the same as the number of dimensions in input.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder(tf.float32, (None, 100))
>>> n = tl.layers.InputLayer(x, name='in')
>>> n = tl.layers.ExpandDimsLayer(n, 2)
>>> n = tl.layers.TileLayer(n, [-1, 1, 3])
... [None, 100, 3]

Stack layer

Stack layer

class tensorlayer.layers.StackLayer(layers, axis=1, name='stack')[source]

The StackLayer class is layer for stacking a list of rank-R tensors into one rank-(R+1) tensor, see tf.stack().

Parameters:
  • layers (list of Layer) – Previous layers to stack.
  • axis (int) – Dimension along which to concatenate.
  • name (str) – A unique layer name.

Examples

>>> x = tf.placeholder(tf.float32, shape=[None, 30])
>>> net = tl.layers.InputLayer(x, name='input')
>>> net1 = tl.layers.DenseLayer(net, 10, name='dense1')
>>> net2 = tl.layers.DenseLayer(net, 10, name='dense2')
>>> net3 = tl.layers.DenseLayer(net, 10, name='dense3')
>>> net = tl.layers.StackLayer([net1, net2, net3], axis=1, name='stack')
... (?, 3, 10)

Unstack layer

tensorlayer.layers.UnStackLayer(layer, num=None, axis=0, name='unstack')

It is layer for unstacking the given dimension of a rank-R tensor into rank-(R-1) tensors., see tf.unstack().

Parameters:
  • layer (Layer) – Previous layer
  • num (int or None) – The length of the dimension axis. Automatically inferred if None (the default).
  • axis (int) – Dimension along which axis to concatenate.
  • name (str) – A unique layer name.
Returns:

The list of layer objects unstacked from the input.

Return type:

list of Layer

Connect TF-Slim

TF-Slim models can be connected into TensorLayer. All Google’s Pre-trained model can be used easily , see Slim-model.

class tensorlayer.layers.SlimNetsLayer(prev_layer, slim_layer, slim_args=None, name='tfslim_layer')[source]

A layer that merges TF-Slim models into TensorLayer.

Models can be found in slim-model, see Inception V3 example on Github.

Parameters:
  • layer (Layer) – Previous layer.
  • slim_layer (a slim network function) – The network you want to stack onto, end with return net, end_points.
  • slim_args (dictionary) – The arguments for the slim model.
  • name (str) – A unique layer name.

Notes

  • As TF-Slim stores the layers as dictionary, the all_layers in this network is not in order ! Fortunately, the all_params are in order.

Parametric activation layer

class tensorlayer.layers.PReluLayer(prev_layer, channel_shared=False, a_init=<tensorflow.python.ops.init_ops.Constant object>, a_init_args=None, name='prelu_layer')[source]

The PReluLayer class is Parametric Rectified Linear layer.

Parameters:
  • layer (Layer) – Previous layer。
  • channel_shared (boolean) – If True, single weight is shared by all channels.
  • a_init (initializer) – The initializer for initializing the alpha(s).
  • a_init_args (dictionary) – The arguments for initializing the alpha(s).
  • name (str) – A unique layer name.

References

Flow control layer

class tensorlayer.layers.MultiplexerLayer(layers, name='mux_layer')[source]

The MultiplexerLayer selects inputs to be forwarded to output. see tutorial_mnist_multiplexer.py.

Parameters:
  • layers (a list of Layer) – The input layers.
  • name (str) – A unique layer name.
sel

placeholder – The placeholder takes an integer for selecting which layer to output.

Examples

>>> x = tf.placeholder(tf.float32, shape=(None, 784), name='x')
>>> # define the network
>>> net_in = tl.layers.InputLayer(x, name='input')
>>> net_in = tl.layers.DropoutLayer(net_in, keep=0.8, name='drop1')
>>> # net 0
>>> net_0 = tl.layers.DenseLayer(net_in, n_units=800, act=tf.nn.relu, name='net0/relu1')
>>> net_0 = tl.layers.DropoutLayer(net_0, keep=0.5, name='net0/drop2')
>>> net_0 = tl.layers.DenseLayer(net_0, n_units=800, act=tf.nn.relu, name='net0/relu2')
>>> # net 1
>>> net_1 = tl.layers.DenseLayer(net_in, n_units=800, act=tf.nn.relu, name='net1/relu1')
>>> net_1 = tl.layers.DropoutLayer(net_1, keep=0.8, name='net1/drop2')
>>> net_1 = tl.layers.DenseLayer(net_1, n_units=800, act=tf.nn.relu, name='net1/relu2')
>>> net_1 = tl.layers.DropoutLayer(net_1, keep=0.8, name='net1/drop3')
>>> net_1 = tl.layers.DenseLayer(net_1, n_units=800, act=tf.nn.relu, name='net1/relu3')
>>> # multiplexer
>>> net_mux = tl.layers.MultiplexerLayer(layers=[net_0, net_1], name='mux')
>>> network = tl.layers.ReshapeLayer(net_mux, shape=(-1, 800), name='reshape')
>>> network = tl.layers.DropoutLayer(network, keep=0.5, name='drop3')
>>> # output layer
>>> network = tl.layers.DenseLayer(network, n_units=10, act=tf.identity, name='output')

Helper functions

Flatten tensor

tensorlayer.layers.flatten_reshape(variable, name='flatten')[source]

Reshapes a high-dimension vector input. [batch_size, mask_row, mask_col, n_mask] —> [batch_size, mask_row x mask_col x n_mask]

Parameters:
  • variable (TensorFlow variable or tensor) – The variable or tensor to be flatten.
  • name (str) – A unique layer name.
Returns:

Flatten Tensor

Return type:

Tensor

Examples

>>> W_conv2 = weight_variable([5, 5, 100, 32])   # 64 features for each 5x5 patch
>>> b_conv2 = bias_variable([32])
>>> W_fc1 = weight_variable([7 * 7 * 32, 256])
>>> h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
>>> h_pool2 = max_pool_2x2(h_conv2)
>>> h_pool2.get_shape()[:].as_list() = [batch_size, 7, 7, 32]
...         [batch_size, mask_row, mask_col, n_mask]
>>> h_pool2_flat = tl.layers.flatten_reshape(h_pool2)
...         [batch_size, mask_row * mask_col * n_mask]
>>> h_pool2_flat_drop = tf.nn.dropout(h_pool2_flat, keep_prob)
...

Permanent clear existing layer names

tensorlayer.layers.clear_layers_name()[source]

DEPRECATED FUNCTION

THIS FUNCTION IS DEPRECATED. It will be removed after 2018-06-30. Instructions for updating: TensorLayer relies on TensorFlow to check naming.

Initialize RNN state

tensorlayer.layers.initialize_rnn_state(state, feed_dict=None)[source]

Returns the initialized RNN state. The inputs are LSTMStateTuple or State of RNNCells, and an optional feed_dict.

Parameters:
  • state (RNN state.) – The TensorFlow’s RNN state.
  • feed_dict (dictionary) – Initial RNN state; if None, returns zero state.
Returns:

The TensorFlow’s RNN state.

Return type:

RNN state

Remove repeated items in a list

tensorlayer.layers.list_remove_repeat(x)[source]

Remove the repeated items in a list, and return the processed list. You may need it to create merged layer like Concat, Elementwise and etc.

Parameters:x (list) – Input
Returns:A list that after removing it’s repeated items
Return type:list

Examples

>>> l = [2, 3, 4, 2, 3]
>>> l = list_remove_repeat(l)
... [2, 3, 4]

Merge networks attributes

tensorlayer.layers.merge_networks(layers=None)[source]

Merge all parameters, layers and dropout probabilities to a Layer. The output of return network is the first network in the list.

Parameters:layers (list of Layer) – Merge all parameters, layers and dropout probabilities to the first layer in the list.
Returns:The network after merging all parameters, layers and dropout probabilities to the first network in the list.
Return type:Layer

Examples

>>> n1 = ...
>>> n2 = ...
>>> n1 = tl.layers.merge_networks([n1, n2])