# tf.sequence_mask

<br />

|---|
| [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png) View source on GitHub](https://github.com/tensorflow/tensorflow/blob/v2.13.1/tensorflow/python/ops/array_ops.py#L4310-L4374) |

Returns a mask tensor representing the first N positions of each cell.

#### View aliases


**Compat aliases for migration**

See
[Migration guide](https://www.tensorflow.org/guide/migrate) for
more details.

[`tf.compat.v1.sequence_mask`](https://www.tensorflow.org/api_docs/python/tf/sequence_mask)

<br />

    tf.sequence_mask(
        lengths,
        maxlen=None,
        dtype=https://www.tensorflow.org/versions/r2.13/api_docs/python/tf/dtypes#bool,
        name=None
    )

If `lengths` has shape `[d_1, d_2, ..., d_n]` the resulting tensor `mask` has
dtype `dtype` and shape `[d_1, d_2, ..., d_n, maxlen]`, with

    mask[i_1, i_2, ..., i_n, j] = (j < lengths[i_1, i_2, ..., i_n])

#### Examples:

    tf.sequence_mask([1, 3, 2], 5)  # [[True, False, False, False, False],
                                    #  [True, True, True, False, False],
                                    #  [True, True, False, False, False]]

    tf.sequence_mask([[1, 3],[2,0]])  # [[[True, False, False],
                                      #   [True, True, True]],
                                      #  [[True, True, False],
                                      #   [False, False, False]]]

<br />

<br />

<br />

| ## Args ||
|---|---|
| `lengths` | integer tensor, all its values \<= maxlen. |
| `maxlen` | scalar integer tensor, size of last dimension of returned tensor. Default is the maximum value in `lengths`. |
| `dtype` | output type of the resulting tensor. |
| `name` | name of the op. |

<br />

<br />

<br />

<br />

| ## Returns ||
|---|---|
| A mask tensor of shape `lengths.shape + (maxlen,)`, cast to specified dtype. ||

<br />

<br />

<br />

<br />

| ## Raises ||
|---|---|
| `ValueError` | if `maxlen` is not a scalar. |

<br />