narrow

paddle. narrow ( input, dim, start, length ) [源代码]

返回输入张量 input 在指定维度 dim 上的窄切片。 该操作保留所有维度,仅沿 dim 选取索引区间 [start, start + length) 内的元素,则返回结果与输入共享内存(视图)。

参数

  • input (Tensor) - 输入张量,支持任意数据类型与形状。

  • dim (int) - 要窄化的维度,支持负索引。

  • start (int|Tensor) - 起始索引,可为 Python 整数或 0-D 的 int32/int64 张量,负值表示从维度末尾倒数。

  • length (int) - 从 start 开始选取的元素个数,必须 ≥ 0。

返回

Tensor,与 input 数据类型相同,形状仅在 dim 维变为 length,其余维不变。

代码示例

>>> 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]])