温馨提示×

pytorch张量拼接怎么实现

小亿
91
2024-01-09 12:46:22
栏目: 编程语言

在PyTorch中,可以使用torch.cat()函数来实现张量的拼接。

torch.cat()函数的语法如下:

torch.cat(tensors, dim=0, out=None)

其中,参数tensors是一个张量的序列,表示要拼接的张量;dim是指定拼接的维度,默认为0(沿着行的方向拼接);out是一个可选的输出张量,表示拼接的结果。

下面是一个使用torch.cat()函数进行张量拼接的示例代码:

import torch

# 创建两个张量
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor2 = torch.tensor([[7, 8, 9], [10, 11, 12]])

# 沿着行的方向拼接张量
result = torch.cat((tensor1, tensor2), dim=0)

print(result)

运行结果为:

tensor([[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]])

在上述示例中,我们首先创建了两个张量tensor1tensor2。然后,通过torch.cat()函数将这两个张量沿着行的方向进行拼接,得到了一个新的张量result。最后,我们打印出了拼接结果。

0