1. 函数介绍
在PyTorch中,torch.cat()函数用于将多个张量(tensors)连接在一起。这个函数接受一个张量序列(通常是一个列表或元组)和一个维度参数dim,并将所有张量沿着指定的维度进行连接。
2. 代码说明
沿着维度0连接
import torch
# 创建两个张量
tensor1 = torch.tensor([1, 2, 3])
tensor2 = torch.tensor([4, 5, 6])
# 沿着维度0(行)连接上述两个张量
result_dim0 = torch.cat((tensor1, tensor2), dim = 0)
print("沿着维度0连接")
print(result_dim0)
输出:
沿着维度0连接
tensor([1, 2, 3, 4, 5, 6])
沿着维度1连接
# 创建两个二维张量
tensor3 = torch.tensor([[1, 2], [3, 4]])
tensor4 = torch.tensor([[5, 6], [7, 8]])
# 沿着维度1(列)连接上述两个张量
result_dim1 = torch.cat((tensor3, tensor4), dim = 1)
print("沿着维度1连接")
print(result_dim1)
输出:
沿着维度1连接
tensor([[1, 2, 5, 6],
[3, 4, 7, 8]])
3. 总结
沿着维度0连接,按照行连接
沿着维度1连接,按照每列连接,把所有列连接成一行