본문 바로가기
파이토치

[Pytorch] Torch.permute() 차원을 변경하는 함수 / Transpose 함수와의 차이점

by 채소사장 2023. 12. 17.
반응형

 

 

torch.permute — PyTorch 2.1 documentation

Shortcuts

pytorch.org

 

공식 문서는 위의 링크를 참고하시면 됩니다. 간단하게 설명하자면 차원의 위치를 변경해주는 함수입니다.

 

Permute()

# z.shape = (batch, channel, height, width)
z = z.permute(0, 2, 3, 1).contiguous()

# z.shape -> (batch, height, width, channel)
z_flattened = z.view(-1, self.e_dim)

 

Parameters

  • input (Tensor) – the input tensor.
  • dims (tuple of int) – The desired ordering of dimensions

batch, channel, height, width순으로 되어있는 입력 z를 받았다고 해봅시다. encoder를 통해서 나온 z는 permute를 통해서 batch, height, width, channel순으로 shape이 변화하게 됩니다.

 

- contiguous는 메모리상에서 tensor가 실제로 연속적으로 할당되도록 해주는 함수

- view는 차원을 펼쳐주는 함수

 

import torch

x = torch.randn(2, 3, 5)


print(x.size())
print(torch.permute(x, (2, 0, 1)).size())

 

 

Permute vs Transpose의 차이점

차원을 변경해주는 함수는 Transpose도 존재하는데 왜 Permute를 사용해야할까?

 

이유는 Transpose는 2개의 차원까지만 교환이 가능하며 permute는 차원의 개수에 상관없이 교환이 가능하다.

 

x = torch.randn(2, 3, 5)

y = x.transpose(0, 2)
print(x.size())
z = x.permute(2, 1, 0)  
print(x.size())

 

 

 

반응형