PyTorch torch.concat function
PyTorch torch reference manual
torch.concat 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.concat(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 two tensors
a
=
torch.
tensor
(
[
1
,
2
,
3
]
)
b
=
torch.
tensor
(
[
4
,
5
,
6
]
)
Concatenate two tensors
result
=
torch.
concat
(
[
a
,
b
]
)
(
result
)
The output is:
tensor([1, 2, 3, 4, 5, 6])
Example
import
torch
Create two 2D tensors
a
=
torch.
tensor
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
b
=
torch.
tensor
(
[
[
5
,
6
]
,
[
7
,
8
]
]
)
Concatenate along the first dimension
c
=
torch.
concat
(
[
a
,
b
]
,
dim
=
0
)
Concatenate along the second dimension
d
=
torch.
concat
(
[
a
,
b
]
,
dim
=
1
)
(
"Concatenate along dim=0:"
)
(
c
)
(
"nConcatenate along dim=1:"
)
(
d
)
The output is:
沿 dim=0 连接:
tensor([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
Connect along dim=1:
tensor([[1, 2, 5, 6],
[3, 4, 7, 8]])
Note:torch.concat Is torch.cat is an alias of it, and the two are functionally identical.