PyTorch torch.repeat_interleave function
PyTorch torch reference manual
torch.repeat_interleave is a function in PyTorch used to repeat elements along a specified dimension.
Function definition
torch.repeat_interleave(input, repeats, dim=None, *, output_size=None)
Usage examples
Example
import
torch
Without specifying dim, repeat along all elements
x
=
torch.
tensor
(
[
1
,
2
,
3
]
)
result
=
torch.
repeat_interleave
(
x
,
2
)
(
"Repeat each element 2 times:"
)
(
result
)
Repeat along dim=0
y
=
torch.
tensor
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
(
"nOriginal tensor:"
)
(
y
)
result
=
torch.
repeat_interleave
(
y
,
2
,
dim
=
0
)
(
"Repeat 2 times along dim=0:"
)
(
result
)
Different repeat counts for each element
result
=
torch.
repeat_interleave
(
y
,
torch.
tensor
(
[
1
,
2
]
)
,
dim
=
0
)
(
"nDifferent repeat counts along dim=0 [1, 2]:"
)
(
result
)
Repeat along dim=1
result
=
torch.
repeat_interleave
(
y
,
3
,
dim
=
1
)
(
"nRepeat 3 times along dim=1:"
)
(
result
)
Return output_size
result
=
torch.
repeat_interleave
(
x
,
2
,
output_size
=
9
)
(
"nSpecify output_size=9:"
)
(
result
)
The output is:
每个元素重复 2 次:
tensor([1, 1, 2, 2, 3, 3])
Original tensor:
tensor([[1, 2],
[3, 4]])
Repeat 2 times along dim=0:
tensor([[1, 2],
[1, 2],
[3, 4],
[3, 4]])
沿 dim=0 不同重复次数 [1, 2]:
tensor([[1, 2],
[3, 4],
[3, 4]])
Repeat 3 times along dim=1:
tensor([[1, 1, 1, 2, 2, 2],
[3, 3, 3, 4, 4, 4]])
指定 output_size=9:
tensor([1, 1, 2, 2, 3, 3, 1, 2, 3])