PyTorch torch.split_with_sizes function
PyTorch torch reference manual
torch.split_with_sizes is a function in PyTorch used to split a tensor by specified sizes.
Function definition
torch.split_with_sizes(input, split_sizes, dim=0)
Usage examples
Example
import
torch
x
=
torch.
arange
(
10
)
(
"Original tensor:"
)
(
x
)
Split by sizes [2, 3, 5]
result
=
torch.
split_with_sizes
(
x
,
[
2
,
3
,
5
]
)
(
"Split result:"
)
for
i
,
t
in
enumerate
(
result
)
:
(
f
" Chunk {i}: {t}"
)
Split a 2D tensor by rows
y
=
torch.
arange
(
12
)
.
reshape
(
4
,
3
)
(
"nOriginal 2D tensor:"
)
(
y
)
result
=
torch.
split_with_sizes
(
y
,
[
1
,
2
,
1
]
,
dim
=
0
)
(
"Split by rows [1, 2, 1]:"
)
for
i
,
t
in
enumerate
(
result
)
:
(
f
" chunk {i}:n{t}"
)
The output is:
原始张量:
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Split results:
块 0: tensor([0, 1])
块 1: tensor([2, 3, 4])
块 2: tensor([5, 6, 7, 8, 9])
Original two-dimensional tensor:
tensor([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
按行分割 [1, 2, 1]:
块 0:
tensor([[0, 1, 2]])
块 1:
tensor([[3, 4, 5],
[6, 7, 8]])
块 2:
tensor([[ 9, 10, 11]])