narrow

paddle. narrow ( input: Tensor, dim: int, start: int | Tensor, length: int ) Tensor [source]

Returns a narrowed slice of input along a single axis.

This operator selects the index range [start, start + length) on dimension dim and keeps all the dimensions unchanged.

Parameters
  • input (Tensor) – Input tensor.

  • dim (int) – Dimension to narrow. Supports negative indexing.

  • start (int|Tensor) – Start index on dim. Can be a Python int or a 0-D int Tensor (int32 or int64). Negative values are supported.

  • length (int) – Number of elements to select from start. Must be non-negative.

Returns

A tensor that is a narrowed view of input.

Return type

Tensor

Examples

>>> import paddle >>> x = paddle.to_tensor([[1, 2, 3, 4], ...  [5, 6, 7, 8]], dtype='int64') >>> y1 = paddle.narrow(x, dim=1, start=1, length=2) >>> print(y1) Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True, [[2, 3],  [6, 7]]) >>> y2 = paddle.narrow(x, dim=-1, start=-3, length=3) >>> print(y2) Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True, [[2, 3, 4],  [6, 7, 8]]) >>> s = paddle.to_tensor(0, dtype='int64') >>> y3 = paddle.narrow(x, dim=1, start=s, length=2) >>> print(y3) Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True, [[1, 2],  [5, 6]])