可以先使用 torch.cat() 函数将列表中的张量在第0维(行)上进行拼接,然后再使用 .view() 函数将形状调整为需要的形状。下面是示例代码:
import torch # 定义要合并的张量列表 tensors = [torch.tensor([[1, 2]]), torch.tensor([[5, 6]]), torch.tensor([[9, 10]])] # 在第0维上拼接张量 result = torch.cat(tensors, dim=0) # 调整形状 result = result.view(-1, 2) print(result) # 输出 tensor([[ 1, 2],[ 5, 6],[ 9, 10]])
在上述代码中,我们首先定义了一个包含三个张量的列表 tensors,然后使用 torch.cat() 函数将这些张量在第0维上进行拼接,得到一个形状为 (3, 2) 的张量。最后,我们使用 .view() 函数将形状调整为 (3, 2),即每行有两个元素的二维张量。