每天讲解一点PyTorch 【2】transpose

今天我们学习transpose函数
transpose函数,它实现的功能是交换维度,也就是矩阵转置功能,不支持高维度

>>> m = torch.tensor([[1,2],[3,4]])
>>> m
tensor([[1, 2],
        [3, 4]])

>>> m.transpose(0,1) 
tensor([[1, 3],
        [2, 4]])
>>> 
>>> n = torch.tensor([[2,3],[4,5]])
>>> n
tensor([[2, 3],
        [4, 5]])
>>> n.transpose(0,1) 
tensor([[2, 4],
        [3, 5]])
>>> 

进一步分析:


```python
>>> a = torch.rand(1,2,3)
>>> a
tensor([
   [
     [0.5346, 0.1114, 0.8110],
     [0.3542, 0.7874, 0.8278]
   ]
])

>>> a.transpose(1,0) #不支持高维度,一次只能2个维度
tensor([
		[
		  [0.5346, 0.1114, 0.8110]
		],
		[
		  [0.3542, 0.7874, 0.8278]
		]
	])

>>> a.transpose(0,1)
tensor([
		[
			[0.5346, 0.1114, 0.8110]
		],
        [
        	[0.3542, 0.7874, 0.8278]
        ]
        ])
        
>>> a.transpose(0,2)
tensor([
 		[
		 [0.5346],[0.3542]
        ],
        [
         [0.1114],[0.7874]
        ],
        [
         [0.8110],[0.8278]
        ]
      ])

>>> a.transpose(2,0)
tensor([[[0.5346],
         [0.3542]],

        [[0.1114],
         [0.7874]],

        [[0.8110],
         [0.8278]]])


>>> a.permute(1,0,2)
tensor([
         [
           [0.5346, 0.1114, 0.8110]
         ],
         [
           [0.3542, 0.7874, 0.8278]
         ]
       ])

>>> a
tensor([[[0.5346, 0.1114, 0.8110],
         [0.3542, 0.7874, 0.8278]]])
>>> 
>>> a.shape
torch.Size([1, 2, 3])
>>> 
>>> a.transpose(-2,-1)
tensor([[[0.5346, 0.3542],
         [0.1114, 0.7874],
         [0.8110, 0.8278]]])
>>> 

你可能感兴趣的:(Deep,Learning,pytorch,python,深度学习)