Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.tensor_split function

PyTorch torch.tensor_split function


PyTorch torch reference manual 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

)

print

(

"Original tensor:"

)

print

(

x

)

Split by index

result

=

torch.

tensor_split

(

x

,

[

2

,

5

,

8

]

)

print

(

"Split by indices [2, 5, 8]:"

)

for

i

,

t

in

enumerate

(

result

)

:

   

print

(

f

" Chunk {i}: {t}"

)

Split by number of sections (divided equally into 3 parts)

y

=

torch.

arange

(

9

)

result

=

torch.

tensor_split

(

y

,

3

)

print

(

"nDivided equally into 3 parts:"

)

for

i

,

t

in

enumerate

(

result

)

:

   

print

(

f

" Chunk {i}: {t}"

)

Split a 2D tensor by columns

z

=

torch.

arange

(

12

)

.

reshape

(

3

,

4

)

print

(

"n2D tensor:"

)

print

(

z

)

result

=

torch.

tensor_split

(

z

,

2

,

dim

=

1

)

print

(

"Divided into 2 parts by columns:"

)

for

i

,

t

in

enumerate

(

result

)

:

   

print

(

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]])


PyTorch torch reference manual PyTorch torch reference manual