torch.repeat_interleave(input, repeats, dim=None, *, output_size=None) → Tensor
例子1:不指定dim, 就会把input拍平(flatten),然后把每个元素重复repeats次
>>> x = torch.tensor([1, 2, 3])
>>> x.repeat_interleave(2)
tensor([1, 1, 2, 2, 3, 3])
>>> y = torch.tensor([[1, 2], [3, 4]])
>>> torch.repeat_interleave(y, 2)
tensor([1, 1, 2, 2, 3, 3, 4, 4])
例子2:指定了dim,就会在dim维度重复repeats次
下面的dim=1指的是最里面的维度,也就是1,2 和 3, 4元素
返回size[2, 2x3]
>>> y = torch.tensor([[1, 2], [3, 4]])
>>> y.shape
torch.Size([2, 2])
>>> torch.repeat_interleave(y, 3, dim=1)
tensor([[1, 1, 1, 2, 2, 2],
[3, 3, 3, 4, 4, 4]])
例子3:不仅指定dim,还要指定dim维度中每个元素分别repeat几次
>>> y = torch.tensor([[1, 2], [3, 4]])
>>> y.shape
torch.Size([2, 2])
>>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0)
tensor([[1, 2],
[3, 4],
[3, 4]])
dim=0指的是两个一维数组[1,2], [3, 4],
torch.tensor([1, 2])指定了[1, 2]重复1次,[3,4]重复2次
返回size(1+1x2, 2)
例子4:指定output_size
如果不指定output_size,那么它是会自动被计算的,
指定的话也不是任意指定的,要计算出重复以后指定的dim上会变成多少,比如如下dim=0经过重复后会变成1+1x2=3,
output_size必须指定成3,不然会报错,
那指定有什么好处呢,指定了torch就不会启动流同步来计算它了。
>>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3)
tensor([[1, 2],
[3, 4],
[3, 4]])