sequence_mask

paddle.nn.functional. sequence_mask ( x, maxlen=None, dtype='int64', name=None ) [source]

SequenceMask Layer

This layer outputs a mask according to the input x and maxlen with data type of dtype.

Supposing x is a Tensor with shape [d_1, d_2, …, d_n], the y is a mask with shape [d_1, d_2, …, d_n, maxlen], where:

\[y(i_1, i_2,..., i_n, j) = (j < x(i_1, i_2,..., i_n))\]
Case:

Consider input:
    x = [3, 1, 1, 0]    max_len = 4

then we get out:
    mask = [[1, 1, 1, 0],
            [1, 0, 0, 0],
            [1, 0, 0, 0],
            [0, 0, 0, 0]]
Parameters
  • x (Variable) – Input tensor of sequence_mask layer, whose elements are integers less than maxlen. Tensor or LodTensor with shape [d_1, d_2, …, d_n].

  • maxlen (int, optional) – Maximum length of the sequence. If maxlen is None, it would be replace with \(max(x)\).

  • dtype (np.dtype|paddle.dtype|str, optional) – Data type of the output, int64 by default.

  • name (str, optional) – For detailed information, please refer to Name. Usually name is no need to set and None by default.

Returns

Tensor, The output sequence mask. Tensor with shape [d_1, d_2, …, d_n, maxlen] and data type of dtype. The data type should be bool, float32, float64, int8, int32 or int64.

Examples

import paddle

lengths = paddle.to_tensor([10, 9, 8])
mask = paddle.nn.functional.sequence_mask(lengths)

print(mask.numpy())
# [[1 1 1 1 1 1 1 1 1 1]
#  [1 1 1 1 1 1 1 1 1 0]
#  [1 1 1 1 1 1 1 1 0 0]]