本文不定期更新Torch对tensor的操作,以便自己翻阅。
torch.arange
包括start但不包括end
torch.arange(start=0, end=10)
output: tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
torch.range
包括start也包括end
torch.range(start=0, end=10)
output: tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
torch.stack
对tensors沿指定维度拼接,但返回的Tensor会多一维
a = torch.rand((2, 3))
b = torch.rand((2, 3))
c = torch.stack((a, b))
a:tensor([[0.5382, 0.3976, 0.8762],
[0.3972, 0.7169, 0.3709]])
b:tensor([[0.1340, 0.2853, 0.2138],
[0.3453, 0.4621, 0.4928]])
c:tensor([[[0.5382, 0.3976, 0.8762],
[0.3972, 0.7169, 0.3709]],
[[0.1340, 0.2853, 0.2138],
[0.3453, 0.4621, 0.4928]]])
torch.cat
对tensors沿指定维度拼接,但返回的Tensor的维数不会变
a = torch.rand((2, 3))
b = torch.rand((2, 3))
c = torch.cat((a, b))
a:tensor([[0.0786, 0.0485, 0.5844],
[0.4046, 0.4808, 0.1020]])
b:tensor([[0.1524, 0.0860, 0.6044],
[0.2269, 0.6359, 0.4811]])
c:tensor([[0.0786, 0.0485, 0.5844],
[0.4046, 0.4808, 0.1020],
[0.1524, 0.0860, 0.6044],
[0.2269, 0.6359, 0.4811]])
torch.meshgrid
分别沿x,y方向复制原tensor
a = torch.rand((3))
b = torch.rand((3))
grid_x, grid_y = torch.meshgrid(a, b)
a:tensor([0.9323, 0.7317, 0.2884])
b:tensor([0.1748, 0.1502, 0.2425])
grid_x:tensor([[0.9323, 0.9323, 0.9323],
[0.7317, 0.7317, 0.7317],
[0.2884, 0.2884, 0.2884]]) grid_y:tensor([[0.1748, 0.1502, 0.2425],
[0.1748, 0.1502, 0.2425],
[0.1748, 0.1502, 0.2425]])
torch.roll
shifts正值表示向下或者向右移(针对二维矩阵的说法,多维的话按照dim的顺序一次移位)
x = torch.randn((2, 2, 2))
a = torch.roll(x, shifts=1, dims=0) # Positive value for move down, Negative value for move up
b = torch.roll(x, shifts=-1, dims=0)
c = torch.roll(x, shifts=1, dims=1) # Positive value for move right, Negative value for move left
d = torch.roll(x, shifts=-1, dims=1)
e = torch.roll(x, shifts=(2, 1), dims=(0, 1))
x: tensor([[[ 0.1849, 1.1720],
[ 0.4960, -1.8808]],
[[ 1.0971, -1.3632],
[ 0.0913, 0.3840]]])
a: tensor([[[ 1.0971, -1.3632],
[ 0.0913, 0.3840]],
[[ 0.1849, 1.1720],
[ 0.4960, -1.8808]]])
b: tensor([[[ 1.0971, -1.3632],
[ 0.0913, 0.3840]],
[[ 0.1849, 1.1720],
[ 0.4960, -1.8808]]])
c: tensor([[[ 0.4960, -1.8808],
[ 0.1849, 1.1720]],
[[ 0.0913, 0.3840],
[ 1.0971, -1.3632]]])
d: tensor([[[ 0.4960, -1.8808],
[ 0.1849, 1.1720]],
[[ 0.0913, 0.3840],
[ 1.0971, -1.3632]]])
e: tensor([[[ 0.4960, -1.8808],
[ 0.1849, 1.1720]],
[[ 0.0913, 0.3840],
[ 1.0971, -1.3632]]])