欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

pytorch view()、transpose()和permute()的区别

程序员文章站 2022-06-13 15:19:04
...

transpose()和permute()的不同
1、torch.transpose()是交换指定的两个维度的内容,permute()则可以一次性交换多个维度,代码示例如下

a = torch.tensor([[[1, 2, 3, 4], [4, 5, 6, 7]], [[7, 8, 9, 10], [10, 11, 12, 13]], [[13, 14, 15, 16], [17, 18, 19, 20]]])
print(a, a.shape)

结果输出:tensor([[[ 1,  2,  3,  4],
         			[ 4,  5,  6,  7]],

        			[[ 7,  8,  9, 10],
         			[10, 11, 12, 13]],

        			[[13, 14, 15, 16],
         			[17, 18, 19, 20]]]) torch.Size([3, 2, 4])


b = a.transpose(1,2)
print(b, b.shape)

结果输出:tensor([[[ 1,  4],
         [ 2,  5],
         [ 3,  6],
         [ 4,  7]],

        [[ 7, 10],
         [ 8, 11],
         [ 9, 12],
         [10, 13]],

        [[13, 17],
         [14, 18],
         [15, 19],
         [16, 20]]]) torch.Size([3, 4, 2])

c = a.permute(2, 1, 0)
print(c, c.shape)

结果输出:tensor([[[ 1,  7, 13],
         [ 4, 10, 17]],

        [[ 2,  8, 14],
         [ 5, 11, 18]],

        [[ 3,  9, 15],
         [ 6, 12, 19]],

        [[ 4, 10, 16],
         [ 7, 13, 20]]]) torch.Size([4, 2, 3])

view和 transpose()、permute()的不同
2、如上所述,transpose和permute是将张量的维度进行变换,而view是将张量拉伸成一维,然后根据传入的维度(也就是想要变换的维度),重构出一个新的张量。代码实例如下所示

a = torch.tensor([[[1, 2, 3, 4], [4, 5, 6, 7]], [[7, 8, 9, 10], [10, 11, 12, 13]], [[13, 14, 15, 16], [17, 18, 19, 20]]])
print(a, a.shape)

结果输出:tensor([[[ 1,  2,  3,  4],
         			[ 4,  5,  6,  7]],

        			[[ 7,  8,  9, 10],
         			[10, 11, 12, 13]],

        			[[13, 14, 15, 16],
         			[17, 18, 19, 20]]]) torch.Size([3, 2, 4])
d = a.view(-1, 4)
print(d, d.shape)
结果输出:tensor([[ 1,  2,  3,  4],
        [ 4,  5,  6,  7],
        [ 7,  8,  9, 10],
        [10, 11, 12, 13],
        [13, 14, 15, 16],
        [17, 18, 19, 20]]) torch.Size([6, 4])

通过以上代码可以看出其区别之处