view, reshape, transpose 비교

반디·2023년 3월 13일
0

PyTorch

목록 보기
1/3

transpose

transpose(input, dim0, dim1)t()
dim1차원과 dim0차원을 transpose하여 return2D 이하의 tensor를 input으로 받아 0차원과 1차원을 transpose
a = torch.randint(0, 10, size = (3, 2))
a_trans = torch.transpose(a, 0, 1)
a_t = a.t()
print("a", a)
print("a.shape", a.shape)
print("after transpose", a_trans)
print("after t()", a_t)

print("after transpose, contiguous?", a_trans.is_contiguous())
print("after t(), contiguous?", a_t.is_contiguous())

transpose 연산을 통해 0차원과 1차원이 바뀐 것을 확인할 수 있습니다; 3 by 2 \rightarrow 2 by 3
또한, transpose와 t()를 수행한 이후의 값인 a_trans와 a_t tensor의 값들은 메모리에 연속적으로 할당되어 있지 않음을 확인할 수 있습니다.

view, reshape

view와 reshape은 공통적으로 tensor의 shape을 바꾸는 작업을 수행합니다. 그러나 view와 reshape은 input의 contiguity에 따른 차이가 있습니다.

viewreshape
contiguous (x) \rightarrow 수행 Xcontiguous (x) \rightarrow copy 하여 reshape 수행
  • view: input tensor의 뷰를 생성한다는 개념으로, view 작업을 통해 얻은 새로운 tensor는 원래 tensor와 데이터를 공유합니다. 따라서 view를 적용하기 위해서는 contiguity 제약 조건을 만족해야 합니다.

  • reshape: input tensor가 contiguity 제약 조건을 만족하지 않는다면, copy 후 작업을 수행합니다.

참고문헌
https://inmoonlight.github.io/2021/03/03/PyTorch-view-transpose-reshape/

profile
꾸준히!

0개의 댓글