PyTorch torch.concatenate function
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:
tensors(Sequence of Tensor): The sequence of tensors to concatenate. All tensors must have the same shape in every dimension except the concatenation dimension.dim(int, optional): The dimension along which to concatenate; defaults to 0.out(Tensor, optional): the output tensor.
Return Value:
torch.Tensor: Returns the concatenated tensor.
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
]
)
(
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
)
(
"Shape of a:"
,
a.
shape
)
(
"Shape of b:"
,
b.
shape
)
(
"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.