본문 바로가기

Activities/메타코드 서포터즈 4기

[Tensor] 메타코드 강의 후기_챕터2: Tensor 다루기 part 3

4. Indexing

원하는 원소나 영역을 특정 부분 뽑고 싶을 때 index를 이용하여 선택

기존의 numpy, pandas의 indexing과 유사!!

 

ex) 

a = torch.tensor([[1,2,3],[4,5,6],[7,8,9]])
a[1][2]

 

==> 결과 

tensor(6)

 

5. Shaping Operation : reshape, squeeze/unsqueeze, stack, cat

텐서의 shape, dimension을 조절하는 방법

여러개의 텐서를 합치는 방법

Tensor.reshape()

모양을 변경할 수 있음

원래 사이즈를 구성하는 각 차원 별 길이의 곱으로 표현 가능하다면 변경 가능

Tensor.shape 이 [x, y] 라면, 총 input size인 x*y의 값으로 표현할 수 있는 차원의 조합이면 가능

 

a = torch.tensor([[1,2,3,4],[5,6,7,8]])

print(a.shape)
print(a)
print(a.reshape([4,2]))
print(a.reshape([1,2,4]))
print(a.reshape([2,2,2]))
print(a.reshape([-1, 4]))
print(a.reshape([-1, 4]).shape)
print(a.reshape([3,4]))

 

==> 결과 

torch.Size([2, 4])

tensor([[1, 2, 3, 4], [5, 6, 7, 8]])

tensor([[1, 2], [3, 4], [5, 6], [7, 8]])

tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]])

tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
tensor([[1, 2, 3, 4], [5, 6, 7, 8]])

torch.Size([2, 4])

 

Tensor.squeeze()

차원의 값이 1인 차원을 제거.

차원의 값이 1인 차원이 여러개인 경우, 차원을 지정하면 해당 차원만 제거된다.

 

a = torch.rand(1, 1, 20, 128)
#print(a.shape)
#print(a.squeeze().shape) # [1, 1, 20, 128] -> [20, 128]

b = torch.rand(1, 20, 1, 128)
print(b.shape)
print(b.squeeze(dim=2).shape)

 

==> 결과

torch.Size([1, 20, 1, 128])

torch.Size([1, 20, 128])

 

torch.cat()

차원의 갯수는 유지되고 해당 차원값이 늘어난다.

합치려는 차원을 제외한 나머지 차원의 경우 두 텐서의 모양이 같이야함

a = torch.rand(5, 24, 50) # [M, N, K]
b = torch.rand(5, 24, 50) # [M, N, K]

output1 = torch.cat([a, b], dim=0) #[M+M, N, K]
print(output1.shape)
output2 = torch.cat([a, b], dim=1) #[M, N+N, K]
print(output2.shape)
output3 = torch.cat([a, b], dim=2) #[M, N, K+K]
print(output3.shape)

 

==> 결과 

torch.Size([10, 24, 50])

torch.Size([5, 48, 50])

torch.Size([5, 24, 100])

 

torch.stack()

텐서를 쌓는 방식으로, 지정하는 차원에 새로운 차원이 생긴다 = 차원의 갯수가 증가한다

합치려는 텐서들의 모든 차원의 모양이 같아야함

a = torch.rand(3, 20, 50) # [M, N, K]
b = torch.rand(3, 20, 50) # [M, N, K]

output = torch.stack([a, b], dim=3)
print(output.shape)
print(output)

 

 


메타코드 4기 서포터즈 활동의 일환으로 작성한 게시글입니다. 

메타코드M (mcode.co.kr)