函数
torch.roll(input, shifts, dims=None)
作用
- 沿给定维度滚动张量输入。
- 超出最后一个位置的元素在第一个位置重新引入。
- 如果 dims 为 None,则张量将在滚动前被展平,然后恢复到原始形状。
参数
- input (Tensor) : 输入张量
- shifts (int or tuple of python: ints) : 张量中元素(按照维度)移动的位置数。
- 如果 shifts 是元组,则 dims 必须与 input 的 shape 大小一致,每个维度都会移动对应的值
- dims (int or tuple of python: ints) :沿着 dims 指定的维度进行滚动
举例 1
import torch
x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2)
print(x)
x1 = torch.roll(x, 1)
print(x1)
注 : 因为函数中没有指定参数 dim,所以操作是会先将 x 展平为 [1, 2, 3, 4, 5, 6, 7, 8]
, 移动 1 位,变成 [8, 1, 2, 3, 4, 5, 6, 7]
,再 reshape 成原来的尺寸,得到 tensor([[8, 1], [2, 3], [4, 5], [6, 7]])
举例 2
import torch
x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2)
print(x)
# tensor([[1, 2],
# [3, 4],
# [5, 6],
# [7, 8]])
x2 = torch.roll(x, 1, 0)
print(x2)
# tensor([[7, 8],
# [1, 2],
# [3, 4],
# [5, 6]])
x3 = torch.roll(x, -1, 0)
print(x3)
# tensor([[3, 4],
# [5, 6],
# [7, 8],
# [1, 2]])
x4 = torch.roll(x, shifts=(2, 1), dims=(0, 1))
print(x4)
# tensor([[6, 5],
# [8, 7],
# [2, 1],
# [4, 3]])