PyTorch中的tensor.permute和tensor.view之间的区别? [英] Difference between tensor.permute and tensor.view in PyTorch?

查看:481
本文介绍了PyTorch中的tensor.permute和tensor.view之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

tensor.permute()tensor.view()有什么区别?

他们似乎在做同样的事情.

They seem to do the same thing.

推荐答案


输入

In [12]: aten = torch.tensor([[1, 2, 3], [4, 5, 6]])

In [13]: aten
Out[13]: 
tensor([[ 1,  2,  3],
        [ 4,  5,  6]])

In [14]: aten.shape
Out[14]: torch.Size([2, 3])


torch.view()将张量整形为其他但兼容的形状.例如,我们的输入张量aten具有形状(2, 3).可以查看为形状为(6, 1)(1, 6)等的张量,


torch.view() reshapes the tensor to a different but compatible shape. For example, our input tensor aten has the shape (2, 3). This can be viewed as tensors of shapes (6, 1), (1, 6) etc.,

# reshaping (or viewing) 2x3 matrix as a column vector of shape 6x1
In [15]: aten.view(6, -1)
Out[15]: 
tensor([[ 1],
        [ 2],
        [ 3],
        [ 4],
        [ 5],
        [ 6]])

In [16]: aten.view(6, -1).shape
Out[16]: torch.Size([6, 1])

或者,也可以将其重新塑形或查看为形状为(1, 6)的行向量,如下所示:

Alternatively, it can also be reshaped or viewed as a row vector of shape (1, 6) as in:

In [19]: aten.view(-1, 6)
Out[19]: tensor([[ 1,  2,  3,  4,  5,  6]])

In [20]: aten.view(-1, 6).shape
Out[20]: torch.Size([1, 6])


tensor.permute()仅用于交换轴.下面的示例将使事情变得清楚:


Whereas tensor.permute() is only used to swap the axes. The below example will make things clear:

In [39]: aten
Out[39]: 
tensor([[ 1,  2,  3],
        [ 4,  5,  6]])

In [40]: aten.shape
Out[40]: torch.Size([2, 3])

# swapping the axes/dimensions 0 and 1
In [41]: aten.permute(1, 0)
Out[41]: 
tensor([[ 1,  4],
        [ 2,  5],
        [ 3,  6]])

# since we permute the axes/dims, the shape changed from (2, 3) => (3, 2)
In [42]: aten.permute(1, 0).shape
Out[42]: torch.Size([3, 2])

您还可以使用负索引执行与以下操作相同的操作:

You can also use negative indexing to do the same thing as in:

In [45]: aten.permute(-1, 0)
Out[45]: 
tensor([[ 1,  4],
        [ 2,  5],
        [ 3,  6]])

In [46]: aten.permute(-1, 0).shape
Out[46]: torch.Size([3, 2])

这篇关于PyTorch中的tensor.permute和tensor.view之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆