Base

LayerType

class paddle.trainer_config_helpers.layers.LayerType

Layer type enumerations.

static is_layer_type(type_name)

If type_name is a layer type.

Parameters:type_name (basestring) – layer type name. Because layer type enumerations are strings.
Returns:True if is a layer_type
Return type:bool

LayerOutput

class paddle.trainer_config_helpers.layers.LayerOutput(name, layer_type, parents=None, activation=None, num_filters=None, img_norm_type=None, size=None, outputs=None)

LayerOutput is output for layer function. It is used internally by several reasons.

  • Check layer connection make sense.

    • FC(Softmax) => Cost(MSE Error) is not good for example.
  • Tracking layer connection.

  • Pass to layer methods as input.

Parameters:
  • name (basestring) – Layer output name.
  • layer_type (basestring) – Current Layer Type. One of LayerType enumeration.
  • activation (BaseActivation.) – Layer Activation.
  • parents (list|tuple) – Layer’s parents.
__repr__()

Disable __repr__ for debug reason. Will be implemented when release

__str__()

Disable __str__ for debug reason. Will be implemented when release

Data layer

data_layer

paddle.trainer_config_helpers.layers.data_layer(*args, **kwargs)

Define DataLayer For NeuralNetwork.

The example usage is:

data = data_layer(name="input",
                  size=1000)
Parameters:
  • name (basestring) – Name of this data layer.
  • size (int) – Size of this data layer.
  • layer_attr (ExtraLayerAttribute.) – Extra Layer Attribute.
Returns:

Layer Output Object.

Return type:

LayerOutput

Fully Connected Layers

fc_layer

paddle.trainer_config_helpers.layers.fc_layer(*args, **kwargs)

Helper for declare fully connected layer.

The example usage is:

fc = fc_layer(input=layer,
              size=1024,
              act=LinearActivation(),
              bias_attr=False)

which is equal to:

with mixed_layer(size=1024) as fc:
    fc += full_matrix_projection(input=layer)
param name:The Layer Name.
type name:basestring
param input:The input layer. Could be a list/tuple of input layer.
type input:LayerOutput|list|tuple
param size:The layer dimension.
type size:int
param act:Activation Type. Default is tanh.
type act:BaseActivation
param param_attr:
 The Parameter Attribute|list.
type param_attr:
 ParameterAttribute
param bias_attr:
 The Bias Attribute. If no bias, then pass False or something not type of ParameterAttribute. None will get a default Bias.
type bias_attr:ParameterAttribute|None|Any
param layer_attr:
 Extra Layer config.
type layer_attr:
 ExtraLayerAttribute|None
return:Layer Name.
rtype:LayerOutput

selective_fc_layer

paddle.trainer_config_helpers.layers.selective_fc_layer(*args, **kwargs)

Selectived fully connected layer. Different from fc_layer, the output of this layer maybe sparse. It requires an additional input to indicate several selected columns for output. If the selected columns is not specified, selective_fc_layer acts exactly like fc_layer.

The simple usage is:

sel_fc = selective_fc_layer(input=input, 128, act=TanhActivation())
Parameters:
  • name (basestring) – The Layer Name.
  • input (LayerOutput|list|tuple) – The input layer.
  • size (int) – The layer dimension.
  • act (BaseActivation) – Activation Type. Default is tanh.
  • param_attr (ParameterAttribute) – The Parameter Attribute.
  • bias_attr (ParameterAttribute|None|Any) – The Bias Attribute. If no bias, then pass False or something not type of ParameterAttribute. None will get a default Bias.
  • layer_attr (ExtraLayerAttribute|None) – Extra Layer config.
Returns:

a object of LayerOutput.

Return type:

LayerOutput

Conv Layers

conv_operator

paddle.trainer_config_helpers.layers.conv_operator(input, filter_size, num_filters, num_channel=None, stride=1, padding=0, filter_size_y=None, stride_y=None, padding_y=None)

Different from img_conv_layer, conv_op is an Operator, which can be used in mixed_layer. And conv_op takes two inputs to perform convolution. The first input is the image and the second is filter kernel. It only support GPU mode.

The example usage is:

op = conv_operator(input=[layer1, layer2],
                   filter_size=3.0,
                   num_filters=64,
                   num_channels=64)
Parameters:
  • input (LayerOutput|list|tuple) – Input layer.
  • filter_size (int) – The x dimension of a filter kernel.
  • filter_size_y (int) – The y dimension of a filter kernel. Since paddle now support rectangular filters, the filter’s shape will be (filter_size, filter_size_y).
  • num_filter (int) – channel of output data.
  • num_channel – channel of input data.
  • stride – The x dimension of the stride.
  • stride_y – The y dimension of the stride.
  • padding (int) – The x dimension of padding.
  • padding_y (int) – The y dimension of padding.
Rtype num_channel:
 

int

Rtype stride:

int

Rtype stride_y:

int

Returns:

A ConvOperator Object.

Return type:

ConvOperator

conv_shift_layer

paddle.trainer_config_helpers.layers.conv_shift_layer(*args, **kwargs)
This layer performs cyclic convolution for two input. For example:
  • a[in]: contains M elements.
  • b[in]: contains N elements (N should be odd).
  • c[out]: contains M elements.
\[c[i] = \sum_{j=-(N-1)/2}^{(N-1)/2}a_{i+j} * b_{j}\]
In this formular:
  • a’s index is computed modulo M.
  • b’s index is computed modulo N.

The example usage is:

conv_shift = conv_shif_layer(input=[layer1, layer2])
Parameters:
  • name (basestring) – layer name
  • input (LayerOutput|list|tuple.) – Input layer.
Returns:

a object of LayerOutput.

Return type:

LayerOutput

img_conv_layer

paddle.trainer_config_helpers.layers.img_conv_layer(*args, **kwargs)

Convolution layer for image. Paddle only support square input currently and thus input image’s width equals height.

The details of convolution layer, please refer UFLDL’s convolution .

The num_channel means input image’s channel number. It may be 1 or 3 when input is raw pixels of image(mono or RGB), or it may be the previous layer’s num_filters * num_group.

There are several group of filter in paddle implementation. Each group will process some channel of inputs. For example, if input num_channel = 256, group = 4, num_filter=32, the paddle will create 32*4 = 128 filters to process inputs. The channels will be split into 4 pieces. First 256/4 = 64 channels will process by first 32 filters. The rest channels will be processed by rest group of filters.

Parameters:
  • name (basestring) – Layer name.
  • input (LayerOutput) – Layer Input.
  • filter_size (int) – The x dimension of a filter kernel.
  • filter_size_y (int) – The y dimension of a filter kernel. Since paddle now support rectangular filters, the filter’s shape will be (filter_size, filter_size_y).
  • num_filters – Each filter group’s number of filter
  • act (BaseActivation) – Activation type. Default is tanh
  • groups (int) – Group size of filters.
  • stride (int) – The x dimension of the stride.
  • stride_y (int) – The y dimension of the stride.
  • padding (int) – The x dimension of the padding.
  • padding_y (int) – The y dimension of the padding.
  • bias_attr (ParameterAttribute|False) – Convolution bias attribute. None means default bias. False means no bias.
  • num_channels (int) – number of input channels. If None will be set automatically from previous output.
  • param_attr (ParameterAttribute) – Convolution param attribute. None means default attribute
  • shared_biases (bool) – Is biases will be shared between filters or not.
  • layer_attr (ExtraLayerAttribute) – Layer Extra Attribute.
Returns:

Layer output.

Return type:

LayerOutput

context_projection

paddle.trainer_config_helpers.layers.context_projection(*args, **kwargs)

Context Projection.

It just simply reorganizes input sequence, combines “context_len” sequence to one context from context_start. “context_start” will be set to -(context_len - 1) / 2 by default. If context position out of sequence length, padding will be filled as zero if padding_attr = False, otherwise it is trainable.

For example, origin sequence is [A B C D E F G], context len is 3, then after context projection and not set padding_attr, sequence will be [ 0AB ABC BCD CDE DEF EFG FG0 ].

Parameters:
  • input (LayerOutput) – Input Sequence.
  • context_len (int) – context length.
  • context_start (int) – context start position. Default is -(context_len - 1)/2
  • padding_attr (bool|ParameterAttribute) – Padding Parameter Attribute. If false, it means padding always be zero. Otherwise Padding is learnable, and parameter attribute is set by this parameter.
Returns:

Projection

Return type:

Projection

Image Pooling Layer

img_pool_layer

paddle.trainer_config_helpers.layers.img_pool_layer(*args, **kwargs)

Image pooling Layer.

The details of pooling layer, please refer ufldl’s pooling .

Parameters:
  • padding (int) – pooling padding
  • name (basestring.) – name of pooling layer
  • input (LayerOutput) – layer’s input
  • pool_size (int) – pooling size
  • num_channels (int) – number of input channel.
  • pool_type (BasePoolingType) – pooling type. MaxPooling or AveragePooling. Default is MaxPooling.
  • stride (int) – stride of pooling.
  • start (int) – start position of pooling operation.
  • layer_attr (ExtraLayerAttribute) – Extra Layer attribute.
Returns:

LayerOutput

Norm Layer

img_cmrnorm_layer

paddle.trainer_config_helpers.layers.img_cmrnorm_layer(*args, **kwargs)

Convolution cross-map-response-normalize layer.

TODO(yuyang18): Add reference and equations, to explain why cmr is work?

Parameters:
  • name (basestring) – layer name.
  • input (LayerOutput) – layer’s input.
  • size (int) – cross map response size.
  • scale (float) – TODO(yuyang18)
  • power (float) – TODO(yuyang18)
  • num_channels – input layer’s filers number or channels. If num_channels is None, it will be set automatically.
  • blocked – TODO(yuyang18)
  • layer_attr (ExtraLayerAttribute) – Extra Layer Attribute.
Returns:

Layer’s output

Return type:

LayerOutput

img_rnorm_layer

paddle.trainer_config_helpers.layers.img_rnorm_layer(*args, **kwargs)

TODO(yuyang18): add comments

TODO(yuyang18): Why it is always not implemented whenever use_gpu or not?

Parameters:
  • name
  • input
  • size
  • scale
  • power
  • num_channels
  • layer_attr
Returns:

batch_norm_layer

paddle.trainer_config_helpers.layers.batch_norm_layer(*args, **kwargs)

Batch Normalization Layer. The notation of this layer as follow.

\(x\) is the input features over a mini-batch.

\[\begin{split}\mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//\ \ mini-batch\ mean \\ \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - \ \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\ \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\ \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\ y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift\end{split}\]

The details of batch normalization please refer to this paper.

Parameters:
  • name (basestring) – layer name.
  • input (LayerOutput) – batch normalization input. Better be linear activation. Because there is an activation inside batch_normalization.
  • batch_norm_type – We have batch_norm and cudnn_batch_norm. batch_norm supports both CPU and GPU. cudnn_batch_norm requires cuDNN version greater or equal to v4 (>=v4). But cudnn_batch_norm is faster and needs less memory than batch_norm. By default (None), we will automaticly select cudnn_batch_norm for GPU and batch_norm for CPU. Otherwise, select batch norm type based on the specified type. If you use cudnn_batch_norm, we suggested you use latest version, such as v5.1.
  • act (BaseActivation) – Activation Type. Better be relu. Because batch normalization will normalize input near zero.
  • num_channels (int) – num of image channels or previous layer’s number of filters. None will automatically get from layer’s input.
  • bias_attr (ParameterAttribute) – \(\beta\), better be zero when initialize. So the initial_std=0, initial_mean=1 is best practice.
  • param_attr (ParameterAttribute) – \(\gamma\), better be one when initialize. So the initial_std=0, initial_mean=1 is best practice.
  • layer_attr (ExtraLayerAttribute) – Extra Layer Attribute.
  • use_global_stats (bool|None.) – whether use moving mean/variance statistics during testing peroid. If None or True, it will use moving mean/variance statistics during testing. If False, it will use the mean and variance of current batch of test data for testing.
  • moving_average_fraction (float.) – Factor used in the moving average computation, referred to as facotr, \(runningMean = newMean*(1-factor) + runningMean*factor\)
Returns:

Layer’s output

Return type:

LayerOutput

sum_to_one_norm_layer

paddle.trainer_config_helpers.layers.sum_to_one_norm_layer(*args, **kwargs)

A layer for sum-to-one normalization, which is used in NEURAL TURING MACHINE.

\[out[i] = \frac {in[i]} {\sum_{k=1}^N in[k]}\]

where \(in\) is a (batchSize x dataDim) input vector, and \(out\) is a (batchSize x dataDim) output vector.

The example usage is:

sum_to_one_norm = sum_to_one_norm_layer(input=layer)
Parameters:
  • input (LayerOutput) – Input layer.
  • name (basestring) – Layer name.
  • layer_attr (ExtraLayerAttribute.) – extra layer attributes.
Returns:

layer name.

Return type:

LayerOutput

Recurrent Layers

recurrent_layer

paddle.trainer_config_helpers.layers.recurrent_layer(*args, **kwargs)

TODO(yuyang18): Add docs

Parameters:
  • input
  • size
  • act
  • bias_attr
  • param_attr
  • name
  • layer_attr
Returns:

lstmemory

paddle.trainer_config_helpers.layers.lstmemory(*args, **kwargs)

Long Short-term Memory Cell.

The memory cell was implemented as follow equations.

\[i_t = \sigma(W_{xi}x_{t} + W_{hi}h_{t-1} + W_{ci}c_{t-1} + b_i)\]\[f_t = \sigma(W_{xf}x_{t} + W_{hf}h_{t-1} + W_{cf}c_{t-1} + b_f)\]\[c_t = f_tc_{t-1} + i_t tanh (W_{xc}x_t+W_{hc}h_{t-1} + b_c)\]\[o_t = \sigma(W_{xo}x_{t} + W_{ho}h_{t-1} + W_{co}c_t + b_o)\]\[h_t = o_t tanh(c_t)\]

NOTE: In paddle’s implementation, the multiply operation \(W_{xi}x_{t}\) , \(W_{xf}x_{t}\), \(W_{xc}x_t\), \(W_{xo}x_{t}\) is not done by lstmemory layer, so it must use a mixed_layer do this full_matrix_projection before lstm is used.

NOTE: This is a low level user interface. You may use network.simple_lstm to config a simple plain lstm layer.

Please refer Generating Sequences With Recurrent Neural Networks if you want to know what lstm is. Link is here.

TODO(yuyang18): Check lstm can input multiple values or not?

Parameters:
  • name (basestring) – The lstmemory layer name.
  • input (LayerOutput) – input layer name.
  • reverse (bool) – is sequence process reversed or not.
  • act (BaseActivation) – activation type, TanhActivation by default. \(h_t\)
  • gate_act (BaseActivation) – gate activation type, SigmoidActivation by default.
  • state_act (BaseActivation) – state activation type, TanhActivation by default.
  • bias_attr (ParameterAttribute|None|False) – Bias attribute. None means default bias. False means no bias.
  • param_attr (ParameterAttribute|None|False) – Parameter Attribute.
  • layer_attr (ExtraLayerAttribute|None) – Extra Layer attribute
Returns:

Layer name.

Return type:

LayerOutput

lstm_step_layer

paddle.trainer_config_helpers.layers.lstm_step_layer(*args, **kwargs)

LSTM Step Layer. It used in recurrent_group. The lstm equations are shown as follow.

\[i_t = \sigma(W_{xi}x_{t} + W_{hi}h_{t-1} + W_{ci}c_{t-1} + b_i)\]\[f_t = \sigma(W_{xf}x_{t} + W_{hf}h_{t-1} + W_{cf}c_{t-1} + b_f)\]\[c_t = f_tc_{t-1} + i_t tanh (W_{xc}x_t+W_{hc}h_{t-1} + b_c)\]\[o_t = \sigma(W_{xo}x_{t} + W_{ho}h_{t-1} + W_{co}c_t + b_o)\]\[h_t = o_t tanh(c_t)\]

The input_ of lstm step is \(Wx_t + Wh_{t-1}\), and user should use mixed_layer and full_matrix_projection to calculate these input vector.

The state of lstm step is \(c_{t-1}\). And lstm step layer will do

\[i_t = \sigma(input + W_{ci}c_{t-1} + b_i)\]\[...\]

This layer contains two outputs. Default output is \(h_t\). The other output is \(o_t\), which name is ‘state’ and can use get_output_layer to extract this output.

Parameters:
  • name (basestring) – Layer’s name.
  • size (int) – Layer’s size. NOTE: lstm layer’s size, should be equal as input.size/4, and should be equal as state.size.
  • input (LayerOutput) – input layer. \(Wx_t + Wh_{t-1}\)
  • state (LayerOutput) – State Layer. \(c_{t-1}\)
  • act (BaseActivation) – Activation type. Default is tanh
  • gate_act (BaseActivation) – Gate Activation Type. Default is sigmoid, and should be sigmoid only.
  • state_act (BaseActivation) – State Activation Type. Default is sigmoid, and should be sigmoid only.
  • bias_attr (ParameterAttribute) – Bias Attribute.
  • layer_attr (ExtraLayerAttribute) – layer’s extra attribute.
Returns:

lstm step’s layer output

Return type:

LayerOutput

grumemory

paddle.trainer_config_helpers.layers.grumemory(*args, **kwargs)

Gate Recurrent Unit Layer.

The memory cell was implemented as follow equations.

1. update gate \(z\): defines how much of the previous memory to keep around or the unit updates its activations. The update gate is computed by:

\[z_t = \sigma(W_{z}x_{t} + U_{z}h_{t-1} + b_z)\]

2. reset gate \(r\): determines how to combine the new input with the previous memory. The reset gate is computed similarly to the update gate:

\[r_t = \sigma(W_{r}x_{t} + U_{r}h_{t-1} + b_r)\]

3. The candidate activation \(\tilde{h_t}\) is computed similarly to that of the traditional recurrent unit:

\[{\tilde{h_t}} = tanh(W x_{t} + U (r_{t} \odot h_{t-1}) + b)\]

4. The hidden activation \(h_t\) of the GRU at time t is a linear interpolation between the previous activation \(h_{t-1}\) and the candidate activation \(\tilde{h_t}\):

\[h_t = (1 - z_t) h_{t-1} + z_t {\tilde{h_t}}\]

NOTE: In paddle’s implementation, the multiply operation \(W_{r}x_{t}\), \(W_{z}x_{t}\) and \(W x_t\) are not computed in gate_recurrent layer. So it must use a mixed_layer with full_matrix_projection or fc_layer to compute them before GRU.

The details can refer to Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling.

The simple usage is:

gru = grumemory(input)
Parameters:
  • name (None|basestring) – The gru layer name.
  • input (LayerOutput.) – input layer.
  • reverse (bool) – Wether sequence process is reversed or not.
  • act (BaseActivation) – activation type, TanhActivation by default. This activation affects the \({\tilde{h_t}}\).
  • gate_act (BaseActivation) – gate activation type, SigmoidActivation by default. This activation affects the \(z_t\) and \(r_t\). It is the \(\sigma\) in the above formula.
  • bias_attr (ParameterAttribute|None|False) – Bias attribute. None means default bias. False means no bias.
  • param_attr (ParameterAttribute|None|False) – Parameter Attribute.
  • layer_attr (ExtraLayerAttribute|None) – Extra Layer attribute
Returns:

Layer name.

Return type:

LayerOutput

gru_step_layer

paddle.trainer_config_helpers.layers.gru_step_layer(*args, **kwargs)
Parameters:
  • input (LayerOutput) –
  • output_mem
  • size
  • act
  • name
  • gate_act
  • bias_attr
  • layer_attr
Returns:

Return type:

LayerOutput

Recurrent Layer Group

get_output_layer

paddle.trainer_config_helpers.layers.get_output_layer(*args, **kwargs)

Get layer’s output by name. In paddle, a layer might return multiple value, but return one layer output. If user want to reference another output beside default output, use get_output_layer first to get another output from input.

Parameters:
  • name (basestring) – Layer’s name.
  • input (LayerOutput) – get output layer’s input. And this layer should contains multiple outputs.
  • arg_name (basestring) – Output name from input.
  • layer_attr – Layer’s extra attribute.
Returns:

Layer’s output

Return type:

LayerOutput

Mixed Layer

mixed_layer

paddle.trainer_config_helpers.layers.mixed_layer(*args, **kwargs)

Mixed Layer. A mixed layer will add all inputs together, then activate. Each inputs is a projection or operator.

There are two styles of usages.

  1. When not set inputs parameter, use mixed_layer like this:
with mixed_layer(size=256) as m:
    m += full_matrix_projection(input=layer1)
    m += identity_projection(input=layer2)
  1. You can also set all inputs when invoke mixed_layer as follows:
m = mixed_layer(size=256,
                input=[full_matrix_projection(input=layer1),
                       full_matrix_projection(input=layer2)])
Parameters:
  • name (basestring) – mixed layer name. Can be referenced by other layer.
  • size (int) – layer size.
  • input – inputs layer. It is an optional parameter. If set, then this function will just return layer’s name.
  • act (BaseActivation) – Activation Type.
  • bias_attr (ParameterAttribute or None or bool) – The Bias Attribute. If no bias, then pass False or something not type of ParameterAttribute. None will get a default Bias.
  • layer_attr (ExtraLayerAttribute) – The extra layer config. Default is None.
Returns:

MixedLayerType object can add inputs or layer name.

Return type:

MixedLayerType

embedding_layer

paddle.trainer_config_helpers.layers.embedding_layer(*args, **kwargs)

Define a embedding Layer.

Parameters:
  • name (basestring) – Name of this embedding layer.
  • input (LayerOutput) – The input layer for this embedding. NOTE: must be Index Data.
  • size (int) – The embedding dimension.
  • param_attr (ParameterAttribute|None) – The embedding parameter attribute. See ParameterAttribute for details.
  • layer_attr (ExtraLayerAttribute|None) – Extra layer Config. Default is None.
Returns:

Embedding Layer output

Return type:

LayerOutput

dotmul_projection

paddle.trainer_config_helpers.layers.dotmul_projection(*args, **kwargs)

1. DotMulProjection if input is a layer. It performs element-wise multiplication with weight.

\[out.row[i] += in.row[i] .* weight\]

where \(.*\) means element-wise multiplication.

The example usage is:

proj = dotmul_projection(input=layer)

2. DotMulOperator if input is a list or tuple. It takes two inputs, performs element-wise multiplication:

\[out.row[i] += scale * (in1.row[i] .* in2.row[i])\]

where \(.*\) means element-wise multiplication, and scale is a config scalar, its default value is one.

The example usage is:

op = dotmul_projection(input=[layer1, layer2],
                       scale=2.0)
Parameters:
  • input (LayerOutput|list|tuple) – Input layer.
  • param_attr (ParameterAttribute) – Parameter config, None if use default.
  • scale (float) – config scalar, default value is one.
Returns:

A DotMulProjection or DotMulOperator Object.

Return type:

DotMulProjection or DotMulOperator

full_matrix_projection

paddle.trainer_config_helpers.layers.full_matrix_projection(*args, **kwargs)

Full Matrix Projection. It performs full matrix multiplication.

\[out.row[i] += in.row[i] * weight\]

There are two styles of usage.

  1. When used in mixed_layer like this, you can only set the input:
with mixed_layer(size=100) as m:
    m += full_matrix_projection(input=layer)
  1. When used as an independant object like this, you must set the size:
proj = full_matrix_projection(input=layer,
                              size=100,
                              param_attr=ParamAttr(name='_proj'))
Parameters:
  • input (LayerOutput) – input layer
  • size (int) – The parameter size. Means the width of parameter.
  • param_attr (ParameterAttribute) – Parameter config, None if use default.
Returns:

A FullMatrixProjection Object.

Return type:

FullMatrixProjection

identity_projection

paddle.trainer_config_helpers.layers.identity_projection(input, offset=None)
  1. IdentityProjection if offset=None. It performs:
\[out.row[i] += in.row[i]\]

The example usage is:

proj = identity_projection(input=layer)

2. IdentityOffsetProjection if offset!=None. It likes IdentityProjection, but layer size may be smaller than input size. It select dimesions [offset, offset+layer_size) from input:

\[out.row[i] += in.row[i + \textrm{offset}]\]

The example usage is:

proj = identity_projection(input=layer,
                           offset=10)

Note that both of two projections should not have any parameter.

Parameters:
  • input (LayerOutput.) – Input Layer.
  • offset (int) – Offset, None if use default.
Returns:

A IdentityProjection or IdentityOffsetProjection Object

Return type:

IdentityProjection or IdentityOffsetProjection

table_projection

paddle.trainer_config_helpers.layers.table_projection(*args, **kwargs)

Table Projection. It selects rows from parameter where row_id is in input_ids.

\[out.row[i] += table.row[ids[i]]\]

where \(out\) is output, \(table\) is parameter, \(ids\) is input_ids, and \(i\) is row_id.

There are two styles of usage.

  1. When used in mixed_layer like this, you can only set the input:
with mixed_layer(size=100) as m:
    m += table_projection(input=layer)
  1. When used as an independant object like this, you must set the size:
proj = table_projection(input=layer,
                        size=100,
                        param_attr=ParamAttr(name='_proj'))
Parameters:
  • input (LayerOutput) – Input layer, which must contains id fields.
  • size (int) – The parameter size. Means the width of parameter.
  • param_attr (ParameterAttribute) – Parameter config, None if use default.
Returns:

A TableProjection Object.

Return type:

TableProjection

trans_full_matrix_projection

paddle.trainer_config_helpers.layers.trans_full_matrix_projection(*args, **kwargs)

Different from full_matrix_projection, this projection performs matrix multiplication, using transpose of weight.

\[out.row[i] += in.row[i] * w^\mathrm{T}\]

\(w^\mathrm{T}\) means transpose of weight. The simply usage is:

proj = trans_full_matrix_projection(input=layer,
                                    size=100,
                                    param_attr=ParamAttr(
                                         name='_proj',
                                         initial_mean=0.0,
                                         initial_std=0.01))
Parameters:
  • input (LayerOutput) – input layer
  • size (int) – The parameter size. Means the width of parameter.
  • param_attr (ParameterAttribute) – Parameter config, None if use default.
Returns:

A TransposedFullMatrixProjection Object.

Return type:

TransposedFullMatrixProjection

Aggregate Layers

pooling_layer

paddle.trainer_config_helpers.layers.pooling_layer(*args, **kwargs)

Pooling layer for sequence inputs, not used for Image.

The example usage is:

seq_pool = pooling_layer(input=layer,
                         pooling_type=AvgPooling(),
                         agg_level=AggregateLevel.EACH_SEQUENCE)
Parameters:
  • agg_level (AggregateLevel) – AggregateLevel.EACH_TIMESTEP or AggregateLevel.EACH_SEQUENCE
  • name (basestring) – layer name.
  • input (LayerOutput) – input layer name.
  • pooling_type (BasePoolingType|None) – Type of pooling, MaxPooling(default), AvgPooling, SumPooling, SquareRootNPooling.
  • bias_attr (ParameterAttribute|None|False) – Bias parameter attribute. False if no bias.
  • layer_attr (ExtraLayerAttribute|None) – The Extra Attributes for layer, such as dropout.
Returns:

layer name.

Return type:

LayerType

last_seq

paddle.trainer_config_helpers.layers.last_seq(*args, **kwargs)

Get Last Timestamp Activation of a sequence.

Parameters:
  • agg_level – Aggregated level
  • name (basestring) – Layer name.
  • input (LayerOutput) – Input layer name.
  • layer_attr (ExtraLayerAttribute.) – extra layer attributes.
Returns:

layer name.

Return type:

LayerOutput

first_seq

paddle.trainer_config_helpers.layers.first_seq(*args, **kwargs)

Get First Timestamp Activation of a sequence.

Parameters:
  • agg_level – aggregation level
  • name (basestring) – Layer name.
  • input (LayerOutput) – Input layer name.
  • layer_attr (ExtraLayerAttribute.) – extra layer attributes.
Returns:

layer name.

Return type:

LayerOutput

concat_layer

paddle.trainer_config_helpers.layers.concat_layer(*args, **kwargs)

Concat all input vector into one huge vector. Inputs can be list of LayerOutput or list of projection.

Parameters:
  • name (basestring) – Layer name.
  • input (list|tuple) – input layers or projections
  • act (BaseActivation) – Activation type.
  • layer_attr (ExtraLayerAttribute) – Extra Layer Attribute.
Returns:

layer’s output

Return type:

LayerOutput

Reshaping Layers

block_expand_layer

paddle.trainer_config_helpers.layers.block_expand_layer(*args, **kwargs)
Expand feature map to minibatch matrix.
  • matrix width is: block_y * block_x * channel
  • matirx height is: outputH * outputW
\[outputH = 1 + (2 * padding_y + imgSizeH - block_y + stride_y - 1) / stride_y\]\[outputW = 1 + (2 * padding_x + imgSizeW - block_x + stride_x - 1) / stride_x\]

The expand method is the same with ExpandConvLayer, but saved the transposed value. After expanding, output.sequenceStartPositions will store timeline. The number of time steps are outputH * outputW and the dimension of each time step is block_y * block_x * channel. This layer can be used after convolution neural network, and before recurrent neural network.

Parameters:
  • input (LayerOutput) – The input layer.
  • channel (int) – The channel number of input layer.
  • block_x (int) – The width of sub block.
  • block_y (int) – The width of sub block.
  • stride_x (int) – The stride size in horizontal direction.
  • stride_y (int) – The stride size in vertical direction.
  • padding_x (int) – The padding size in horizontal direction.
  • padding_y (int) – The padding size in vertical direction.
  • name (None|basestring.) – The name of this layer, which can not specify.
Returns:

a object of LayerOutput.

Return type:

LayerOutput

expand_layer

paddle.trainer_config_helpers.layers.expand_layer(*args, **kwargs)

A layer for “Expand Dense data or (sequence data where the length of each sequence is one) to sequence data.”

The example usage is:

expand = expand_layer(input=layer1,
                      expand_as=layer2,
                      expand_level=ExpandLevel.FROM_TIMESTEP)
Parameters:
  • input (LayerOutput) – Input layer
  • expand_as (LayerOutput) – Expand as this layer’s sequence info.
  • name (basestring) – Layer name.
  • bias_attr (ParameterAttribute|None|False) – Bias attribute. None means default bias. False means no bias.
  • expand_level (ExpandLevel) – whether input layer is timestep(default) or sequence.
  • layer_attr (ExtraLayerAttribute.) – extra layer attributes.
Returns:

layer name

Return type:

LayerOutput

Math Layers

addto_layer

paddle.trainer_config_helpers.layers.addto_layer(*args, **kwargs)

AddtoLayer.

\[y = f(\sum_{i} x_i + b)\]

where \(y\) is output, \(x\) is input, \(b\) is bias, and \(f\) is activation function.

The example usage is:

addto = addto_layer(input=[layer1, layer2],
                    act=ReluActivation(),
                    bias_attr=False)

This layer just simply add all input layers together, then activate the sum inputs. Each input of this layer should be the same size, which is also the output size of this layer.

There is no weight matrix for each input, because it just a simple add operation. If you want to a complicated operation before add, please use mixed_layer.

It is a very good way to set dropout outside the layers. Since not all paddle layer support dropout, you can add an add_to layer, set dropout here. Please refer to dropout_layer for details.

Parameters:
  • name (basestring) – Layer name.
  • input (LayerOutput|list|tuple) – Input layers. It could be a LayerOutput or list/tuple of LayerOutput.
  • act (BaseActivation) – Activation Type, default is tanh.
  • bias_attr (ParameterAttribute|bool) – Bias attribute. If False, means no bias. None is default bias.
  • layer_attr (ExtraLayerAttribute) – Extra Layer attribute.
Returns:

layer’s output

Return type:

LayerOutput

convex_comb_layer

paddle.trainer_config_helpers.layers.convex_comb_layer(*args, **kwargs)
A layer for convex weighted average of vectors takes two inputs.
  • Input: a vector containing the convex weights (batchSize x weightdim),

    and a matrix in a vector form (batchSize x (weightdim*datadim)).

  • Output: a vector (batchSize * datadim).

\[y[i][j] = \sum_{j}(x_{1}(i, j) * x_{2}(i,j + i * dataDim)),\]\[ i = 0,1,...,(batchSize-1); j = 0, 1,...,(dataDim-1)\]
In this formular:
  • \(x_{1}\): the first input.
  • \(x_{2}\): the second input.
  • \(y\): the output.

The simple usage is:

convex_comb = convex_comb_layer(input=inputs,
                                size=elem_dim)
Parameters:
  • input (LayerOutput) – The input layers.
  • size (int) – the dimension of this layer.
  • name (basestring) – The Layer Name.
Returns:

a object of LayerOutput.

Return type:

LayerOutput

interpolation_layer

paddle.trainer_config_helpers.layers.interpolation_layer(*args, **kwargs)

This layer is for linear interpolation with two inputs, which is used in NEURAL TURING MACHINE.

\[y.row[i] = w[i] * x_1.row[i] + (1 - w[i]) * x_2.row[i]\]

where \(x_1\) and \(x_2\) are two (batchSize x dataDim) inputs, \(w\) is (batchSize x 1) weight vector, and \(y\) is (batchSize x dataDim) output.

The example usage is:

interpolation = interpolation_layer(input=[layer1, layer2], weight=layer3)
Parameters:
  • input (list|tuple) – Input layer.
  • weight (LayerOutput) – Weight layer.
  • name (basestring) – Layer name.
  • layer_attr (ExtraLayerAttribute.) – extra layer attributes.
Returns:

layer name.

Return type:

LayerOutput

power_layer

paddle.trainer_config_helpers.layers.power_layer(*args, **kwargs)

This layer applies a power function to a vector element-wise, which is used in NEURAL TURING MACHINE.

\[y = x^w\]

where \(x\) is a input vector, \(w\) is scalar weight, and \(y\) is a output vector.

The example usage is:

power = power_layer(input=layer1, weight=layer2)
Parameters:
  • input (LayerOutput) – Input layer.
  • weight (LayerOutput) – Weight layer.
  • name (basestring) – Layer name.
  • layer_attr (ExtraLayerAttribute.) – extra layer attributes.
Returns:

layer name.

Return type:

LayerOutput

scaling_layer

paddle.trainer_config_helpers.layers.scaling_layer(*args, **kwargs)

A layer for each row of a matrix, multiplying with a element of a vector.

\[y.row[i] = w[i] * x.row[i]\]

where \(x\) is (batchSize x dataDim) input, \(w\) is (batchSize x 1) weight vector, and \(y\) is (batchSize x dataDim) output.

The example usage is:

scale = scaling_layer(input=layer1, weight=layer2)
Parameters:
  • input (LayerOutput) – Input layer.
  • weight (LayerOutput) – Weight layer.
  • name (basestring) – Layer name.
  • layer_attr (ExtraLayerAttribute.) – extra layer attributes.
Returns:

layer name.

Return type:

LayerOutput

slope_intercept_layer

paddle.trainer_config_helpers.layers.slope_intercept_layer(*args, **kwargs)

This layer for applying a slope and an intercept to the input element-wise. There is no activation and weight.

\[y = slope * x + intercept\]

The simple usage is:

scale = slope_intercept_layer(input=input, slope=-1.0, intercept=1.0)
Parameters:
  • input (LayerOutput) – The input layer.
  • name (basestring) – The Layer Name.
  • slope (float.) – the scale factor.
  • intercept (float.) – the offset.
Returns:

a object of LayerOutput.

Return type:

LayerOutput

tensor_layer

paddle.trainer_config_helpers.layers.tensor_layer(*args, **kwargs)

This layer performs tensor operation for two input. For example, each sample:

\[y_{i} = x_{1} * W_{i} * {x_{2}^\mathrm{T}}, i=0,1,...,K-1\]
In this formular:
  • \(x_{1}\): the first input contains M elements.
  • \(x_{2}\): the second input contains N elements.
  • y[out]: contains K elements.
  • \(y_{i}\): the i-th element of y.
  • \(W_{i}\): the i-th learned weight, shape if [M, N]
  • \({x_{2}}^\mathrm{T}\): the transpose of \(x_{2}\).

The simple usage is:

tensor = tensor_layer(input=[layer1, layer2])
Parameters:
  • name (basestring) – layer name
  • input (LayerOutput|list|tuple.) – Input layer.
  • size – the layer dimension.
  • act (BaseActivation) – Activation Type. Default is tanh.
  • param_attr (ParameterAttribute|list) – The Parameter Attribute.
  • bias_attr (ParameterAttribute|None|Any) – The Bias Attribute. If no bias, then pass False or something not type of ParameterAttribute. None will get a default Bias.
  • layer_attr (ExtraLayerAttribute|None) – Extra Layer config.
Return type:

int.

Returns:

a object of LayerOutput.

Return type:

LayerOutput

trans_layer

paddle.trainer_config_helpers.layers.trans_layer(*args, **kwargs)

A layer for transposition.

\[y = x^\mathrm{T}\]

where \(x\) is (M x N) input, and \(y\) is (N x M) output.

The example usage is:

trans = trans_layer(input=layer)
Parameters:
  • input (LayerOutput) – Input layer.
  • name (basestring) – Layer name.
  • layer_attr (ExtraLayerAttribute.) – extra layer attributes.
Returns:

layer name.

Return type:

LayerOutput

Sampling Layers

maxid_layer

paddle.trainer_config_helpers.layers.maxid_layer(*args, **kwargs)

A layer for finding the id which has the maximal value for each sample. The result is stored in output.ids.

The example usage is:

maxid = maxid_layer(input=layer)
Parameters:
  • input (LayerOutput) – Input layer name.
  • name (basestring) – Layer name.
  • layer_attr (ExtraLayerAttribute.) – extra layer attributes.
Returns:

layer name.

Return type:

LayerOutput

sampling_id_layer

paddle.trainer_config_helpers.layers.sampling_id_layer(*args, **kwargs)

A layer for sampling id from multinomial distribution from the input layer. Sampling one id for one sample.

The simple usage is:

samping_id = sampling_id_layer(input=input)
Parameters:
  • input (LayerOutput) – The input layer.
  • name (basestring) – The Layer Name.
Returns:

a object of LayerOutput.

Return type:

LayerOutput

Cost Layers

cross_entropy

paddle.trainer_config_helpers.layers.cross_entropy(*args, **kwargs)

A loss layer for multi class entropy.

cost = cross_entropy(input, label)
Parameters:
  • input (LayerOutput.) – The first input layer.
  • label – The input label.
  • type (basestring.) – The type of cost.
  • name (None|basestring.) – The name of this layers. It is not necessary.
  • coeff (float.) – The coefficient affects the gradient in the backward.
Returns:

a object of LayerOutput.

Return type:

LayerOutput.

cross_entropy_with_selfnorm

paddle.trainer_config_helpers.layers.cross_entropy_with_selfnorm(*args, **kwargs)

A loss layer for multi class entropy with selfnorm.

cost = cross_entropy_with_selfnorm(input, label)
Parameters:
  • input (LayerOutput.) – The first input layer.
  • label – The input label.
  • type (basestring.) – The type of cost.
  • name (None|basestring.) – The name of this layers. It is not necessary.
  • coeff (float.) – The coefficient affects the gradient in the backward.
  • softmax_selfnorm_alpha (float.) – The scale factor affects the cost.
Returns:

a object of LayerOutput.

Return type:

LayerOutput.

multi_binary_label_cross_entropy

paddle.trainer_config_helpers.layers.multi_binary_label_cross_entropy(*args, **kwargs)

A loss layer for multi binary label cross entropy.

cost = multi_binary_label_cross_entropy(input, label)
Parameters:
  • input (LayerOutput) – The first input layer.
  • label – The input label.
  • type (basestring) – The type of cost.
  • name (None|basestring) – The name of this layers. It is not necessary.
  • coeff (float) – The coefficient affects the gradient in the backward.
Returns:

a object of LayerOutput.

Return type:

LayerOutput

huber_cost

paddle.trainer_config_helpers.layers.huber_cost(*args, **kwargs)

A loss layer for huber loss.

cost = huber_cost(input, label)
Parameters:
  • input (LayerOutput.) – The first input layer.
  • label – The input label.
  • type (basestring.) – The type of cost.
  • name (None|basestring.) – The name of this layers. It is not necessary.
  • coeff (float.) – The coefficient affects the gradient in the backward.
Returns:

a object of LayerOutput.

Return type:

LayerOutput.

lambda_cost

paddle.trainer_config_helpers.layers.lambda_cost(*args, **kwargs)

lambdaCost for lambdaRank LTR approach.

The simple usage:

cost = lambda_cost(input=input,
                   score=score,
                   NDCG_num=8,
                   max_sort_size=-1)
Parameters:
  • input (LayerOutput) – The 1st input. Samples of the same query should be loaded as sequence. User should provided socres for each sample. The score should be the 2nd input of this layer.
  • score – The 2nd input. Score of each sample.
  • NDCG_num (int) – The size of NDCG (Normalized Discounted Cumulative Gain), e.g., 5 for NDCG@5. It must be less than for equal to the minimum size of lists.
  • max_sort_size (int) – The size of partial sorting in calculating gradient. If max_sort_size = -1, then for each list, the algorithm will sort the entire list to get gradient. In other cases, max_sort_size must be greater than or equal to NDCG_num. And if max_sort_size is greater than the size of a list, the algorithm will sort the entire list of get gradient.
  • name (None|basestring) – The name of this layers. It is not necessary.
  • coeff (float) – The coefficient affects the gradient in the backward.
Returns:

a object of LayerOutput.

Return type:

LayerOutput

rank_cost

paddle.trainer_config_helpers.layers.rank_cost(*args, **kwargs)

A cost Layer for leanrning to rank using gradient descent. Details can refer to papers. This layer contains at least three inputs. The weight is an optional argument, which affects the cost.

\[C_{i,j} = -\tilde{P_{ij}} * o_{i,j} + log(1 + e^{o_{i,j}})\]\[o_{i,j} = o_i - o_j\]\[\tilde{P_{i,j}} = \{0, 0.5, 1\} \ or \ \{0, 1\}\]
In this formula:
  • \(C_{i,j}\) is the cross entropy cost.
  • \(\tilde{P_{i,j}}\) is the label. 1 means positive order and 0 means reverse order.
  • \(o_i\) and \(o_j\): the left output and right output. Their dimension is one.

The simple usage:

cost = rank_cost(left=out_left,
                 right=out_right,
                 label=label)
Parameters:
  • left (LayerOutput) – The first input, the size of this layer is 1.
  • right (LayerOutput) – The right input, the size of this layer is 1.
  • label (LayerOutput) – Label is 1 or 0, means positive order and reverse order.
  • weight (LayerOutput) – The weight affects the cost, namely the scale of cost. It is an optional argument.
  • name (None|basestring) – The name of this layers. It is not necessary.
  • coeff (float) – The coefficient affects the gradient in the backward.
Returns:

a object of LayerOutput.

Return type:

LayerOutput

cos_sim

paddle.trainer_config_helpers.layers.cos_sim(*args, **kwargs)

Cosine Similarity Layer. The cosine similarity equation is here.

\[similarity = cos(\theta) = {\mathbf{A} \cdot \mathbf{B} \over \|\mathbf{A}\| \|\mathbf{B}\|}\]

And the input dimension is \(a \in R^M\), \(b \in R^{MN}\). The similarity will be calculated N times by step M. The output dimension is \(R^N\). The scale will be multiplied to similarity.

Parameters:
  • name (basestring) – layer name
  • a (LayerOutput) – input layer a
  • b (LayerOutput) – input layer b
  • scale (float) – scale for cosine value. default is 5.
  • size (int) – layer size. NOTE size_a * size should equal size_b.
  • layer_attr (ExtraLayerAttribute) – Extra Layer Attribute.
Returns:

layer name.

Return type:

LayerOutput

crf_layer

paddle.trainer_config_helpers.layers.crf_layer(*args, **kwargs)

A layer for calculating the cost of sequential conditional random field model.

The simple usage:

crf = crf_layer(input=input,
                label=label,
                size=label_dim)
Parameters:
  • input (LayerOutput) – The first input layer is the feature.
  • label – The second input layer is label.
  • size (int) – The category number.
  • weight (LayerOutput) – The third layer is “weight” of each sample, which is an optional argument.
  • param_attr (ParameterAttribute) – Parameter attribute. None means default attribute
  • name (None|basestring) – The name of this layers. It is not necessary.
Returns:

a object of LayerOutput.

Return type:

LayerOutput

crf_decoding_layer

paddle.trainer_config_helpers.layers.crf_decoding_layer(*args, **kwargs)

A layer for calculating the decoding sequence of sequential conditional random field model. The decoding sequence is stored in output.ids. If a second input is provided, it is treated as the ground-truth label, and this layer will also calculate error. output.value[i] is 1 for incorrect decoding or 0 for correct decoding.

Parameters:
  • input (LayerOutput) – The first input layer.
  • size (int) – size of this layer.
  • label (LayerOutput or None) – None or ground-truth label.
  • param_attr (ParameterAttribute) – Parameter attribute. None means default attribute
  • name (None|basestring) – The name of this layers. It is not necessary.
Returns:

a object of LayerOutput.

Return type:

LayerOutput

ctc_layer

paddle.trainer_config_helpers.layers.ctc_layer(*args, **kwargs)

Connectionist Temporal Classification (CTC) is designed for temporal classication task. That is, for sequence labeling problems where the alignment between the inputs and the target labels is unknown.

The simple usage:

ctc = ctc_layer(input=input,
                label=label,
                size=9055,
                norm_by_times=True)
Parameters:
  • input (LayerOutput) – The input layers.
  • label (LayerOutput) – The data layer of label with variable length.
  • size (int) – category numbers.
  • name (string|None) – The name of this layer, which can not specify.
  • norm_by_times (bool) – Whether to normalization by times. False by default.
Returns:

a object of LayerOutput.

Return type:

LayerOutput

hsigmoid

paddle.trainer_config_helpers.layers.hsigmoid(*args, **kwargs)

Organize the classes into a binary tree. At each node, a sigmoid function is used to calculate the probability of belonging to the right branch. This idea is from “F. Morin, Y. Bengio (AISTATS 05): Hierarchical Probabilistic Neural Network Language Model.”

The example usage is:

cost = hsigmoid(input=[layer1, layer2],
                label=data_layer,
                num_classes=3)
Parameters:
  • name (basestring) – layer name
  • input (LayerOutput|list|tuple) – Input layers. It could be a LayerOutput or list/tuple of LayerOutput.
  • label (LayerOutput) – Label layer.
  • num_classes (int) – number of classes.
  • bias_attr (ParameterAttribute|False) – Bias attribute. None means default bias. False means no bias.
  • layer_attr (ExtraLayerAttribute) – Extra Layer Attribute.
Returns:

layer name.

Return type:

LayerOutput

Check Layer

eos_layer

paddle.trainer_config_helpers.layers.eos_layer(*args, **kwargs)

A layer for checking EOS for each sample: - output_id = (input_id == conf.eos_id)

The result is stored in output_.ids. It is used by recurrent layer group.

The example usage is:

eos = eos_layer(input=layer, eos_id=id)
Parameters:
  • input (LayerOutput) – Input layer name.
  • eos_id (int) – end id of sequence
  • name (basestring) – Layer name.
  • layer_attr (ExtraLayerAttribute.) – extra layer attributes.
Returns:

layer name.

Return type:

LayerOutput