torch.cat
是 PyTorch 中用于连接张量的函数,它可以沿着指定的维度(轴)将多个张量连接在一起。以下是对 torch.cat
用法的详细解释和一些示例:
import torch
# 创建两个张量
tensor1 = torch.tensor([[1, 2], [3, 4]])
tensor2 = torch.tensor([[5, 6], [7, 8]])
# 沿第0维(行)连接
result1 = torch.cat((tensor1, tensor2), dim=0)
print(result1)
# 输出:
# tensor([[1, 2],
# [3, 4],
# [5, 6],
# [7, 8]])
# 沿第1维(列)连接
result2 = torch.cat((tensor1, tensor2), dim=1)
print(result2)
# 输出:
# tensor([[1, 2, 5, 6],
# [3, 4, 7, 8]])