PyTorch torch.tensor_split function
PyTorch torch reference manual
torch.tensor_split is a function in PyTorch used to split a tensor by indices or by a number of sections.
Function definition
torch.tensor_split(input, indices_or_sections, dim=0)
Usage examples
Example
import
torch
x
=
torch.
arange
(
12
)
(
"Original tensor:"
)
(
x
)
Split by index
result
=
torch.
tensor_split
(
x
,
[
2
,
5
,
8
]
)
(
"Split by indices [2, 5, 8]:"
)
for
i
,
t
in
enumerate
(
result
)
:
(
f
" Chunk {i}: {t}"
)
Split by number of sections (divided equally into 3 parts)
y
=
torch.
arange
(
9
)
result
=
torch.
tensor_split
(
y
,
3
)
(
"nDivided equally into 3 parts:"
)
for
i
,
t
in
enumerate
(
result
)
:
(
f
" Chunk {i}: {t}"
)
Split a 2D tensor by columns
z
=
torch.
arange
(
12
)
.
reshape
(
3
,
4
)
(
"n2D tensor:"
)
(
z
)
result
=
torch.
tensor_split
(
z
,
2
,
dim
=
1
)
(
"Divided into 2 parts by columns:"
)
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, 10, 11])
Split by indices [2, 5, 8]:
块 0: tensor([0, 1])
块 1: tensor([2, 3, 4])
块 2: tensor([5, 6, 7])
块 3: tensor([ 8, 9, 10, 11])
Divided into 3 parts on average:
块 0: tensor([0, 1, 2])
块 1: tensor([3, 4, 5])
块 2: tensor([6, 7, 8])
Two-dimensional tensor:
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
Split into 2 columns:
块 0:
tensor([[0, 1],
[4, 5],
[8, 9]])
块 1:
tensor([[ 2, 3],
[ 6, 7],
[10, 11]])