PyTorch torch.concat Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.concatis a function in PyTorch used to concatenate multiple tensors along a specified dimension. Ittorch.catis the same function, used to concatenate 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 all dimensions except the concatenation dimension.
  • dim(int, optional): The dimension along which to concatenate, default is 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])

print(result)

The output result 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)

print("Concatenation along dim=0:")
print(c)
print("nConcatenation along dim=1:")
print(d)

The output result is:

沿 dim=0 连接:
tensor([[1, 2],
        [3, 4],
        [5, 6],
        [7, 8]])

沿 dim=1 连接:
tensor([[1, 2, 5, 6],
        [3, 4, 7, 8]])

Note:torch.concatYestorch.catis an alias, and the functionality of the two is exactly the same.


Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions