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

PyTorch torch.concatenate function

PyTorch torch.concatenate function


PyTorch torch reference manual PyTorch torch reference manual

torch.concatenate is a function in PyTorch used to concatenate multiple tensors along a specified dimension. It is torch.cat the same function, used to join multiple tensors along a specified dimension into a larger tensor.

Function definition

torch.concatenate(tensors, dim=0, out=None)

Parameters:

Return Value:


Usage examples

Example

import

torch

Create multiple tensors

a

=

torch.

tensor

(

[

1

,

2

]

)

b

=

torch.

tensor

(

[

3

,

4

]

)

c

=

torch.

tensor

(

[

5

,

6

]

)

Concatenate multiple tensors

result

=

torch.

concatenate

(

[

a

,

b

,

c

]

)

print

(

result

)

The output is:

tensor([1, 2, 3, 4, 5, 6])

Example

import

torch

Create two 2D tensors

a

=

torch.

randn

(

2

,

3

)

b

=

torch.

randn

(

2

,

3

)

Concatenate along the first dimension

c

=

torch.

concatenate

(

[

a

,

b

]

,

dim

=

0

)

print

(

"Shape of a:"

,

a.

shape

)

print

(

"Shape of b:"

,

b.

shape

)

print

(

"Shape of c:"

,

c.

shape

)

The output is:

a 的形状: torch.Size([2, 3])

b 的形状: torch.Size([2, 3])

c 的形状: torch.Size([4, 3])


Note:torch.concatenate Is torch.cat is an alias of it, and the two are functionally identical. In real code, the more commonly used one is torch.cat.


PyTorch torch reference manual PyTorch torch reference manual