Tensor dimension에 관하여

Hyoeun·2022년 10월 1일
1
post-thumbnail

1d tensor

>> x = torch.tensor([1, 2, 3])
>> torch.sum(x)
tensor(6)

1차원 텐서를 다룰 때는 직관적으로 이해할 수 있습니다. 그러나 그 이상을 넘어가면 이해하기 어려울 수 있습니다.

  • torch.sum의 Description을 보면 각 주어진 dim의 row를 더한다고 되어 있지만 이 역시 바로 이해하기 힘듭니다.

  • numpy.sumaxis parameter도 torch.sumdim과 같은 역할을 합니다.

2d tensor

>> x = torch.tensor([
					 [1, 2, 3],
					 [4, 5, 6]
                   ])
>> x.shape
torch.Size([2, 3])
  • 위의 2d tensor에서 dim = 0 : row, dim = 1 : column인 것을 쉽게 알 수 있습니다.
  • 그렇다면 x.sum(dim = 0)row-wise로 summation을 구하여 tensor([6, 15])를 내놓을까요?
>> x.sum(dim = 0)
tensor([5, 7, 9])
  • 결과는 오히려 column-wise한 summation을 return했습니다.
  • dim = 1 또한 반대의 결과를 가져옵니다.
>> x.sum(dim = 1)
tensor([6, 15])
  • Aerin Kim님의 article에서 dimension의 이해를 위한 핵심적인 문장을 볼 수 있었습니다.

The way to understand the “axis” of numpy sum is that it collapses the specified axis. So when it collapses the axis 0 (the row), it becomes just one row (it sums column-wise).

numpy.sum의 axis를 이해하려면, 그것(axis parameter)이 특정 axis를 접는다고 생각하면 됩니다. axis 0(row)를 접는다면, 그것은 1개의 row가 되고 column-wise한 sum을 계산합니다. numpy axis == torch dim

Over 3d tensor

>> x = torch.tensor([
     [
       [1, 2, 3],
       [4, 5, 6]
     ],
     [
       [1, 2, 3],
       [4, 5, 6]
     ],
     [
       [1, 2, 3],
       [4, 5, 6]
     ]
   ])
>> x.shape
torch.Size([3, 2, 3])
  • 3 차원(row, col) 이상의 차원이 추가되면 shape의 가장 앞쪽에 추가됩니다.(dim = 0)
  • 위 tensor에서 첫 번째 차원 dim = 0 은 3개의 2d tensor를 포함합니다.
  • 각 2d tensor의 shape은 2 x 3 으로 구성됩니다 [[1,2,3], [4,5,6]]
  • 2 x 3 tensor 3개를 summation하면 2 x 3 tensor가 나옵니다
>> x.sum(dim = 0)
tensor([[ 3,  6,  9],
        [12, 15, 18]])

  • 마찬가지로 dim = 1으로 summation하면 3 x 2 x 3 중 2가 사라져 3 x 3이 나옵니다
>> x.sum(dim = 1)
tensor([[5, 7, 9],
       [5, 7, 9],
       [5, 7, 9]])

  • 해당 애니메이션이 이해를 크게 도와줄 것으로 생각합니다.
  • 이러한 dim의 개념(혹은 axis)은 sum method뿐만이 아니라 폭넓게 적용됩니다.

해당 포스트는 https://towardsdatascience.com/understanding-dimensions-in-pytorch-6edf9972d3be 를 참고하여 작성하였습니다.

0개의 댓글