PyTorch 텐서 조작하기 (2)

IngCoding·2022년 6월 15일
1

머신러닝

목록 보기
7/34

1. 뷰(View)

  • 원소의 수를 유지하면서 텐서의 크기 변경. 매우 중요!!

  • view(), squeeze(), unsqueeze()는 텐서의 원소 수를 그대로 유지하면서 모양과 차원을 조절합니다.

import numpy as np
t = np.array([[[0, 1, 2],
               [3, 4, 5]],
              [[6, 7, 8],
               [9, 10, 11]]])
ft = torch.FloatTensor(t) # 3차원 텐서 (원소 수 12)
print(ft.shape) 
torch.Size([2, 2, 3])
print(ft.view([-1, 3])) # view를 통해 ft라는 텐서 크기 변경 (?, 3)
print(ft.view([-1, 3]).shape) 
tensor([[ 0.,  1.,  2.],
        [ 3.,  4.,  5.],
        [ 6.,  7.,  8.],
        [ 9., 10., 11.]])
torch.Size([4, 3])
print(ft.view([-1, 1, 3])) # -1은 크기설정을 파이토치에게 맡기겠다는 의미 
print(ft.view([-1, 1, 3]).shape)
tensor([[[ 0.,  1.,  2.]],

        [[ 3.,  4.,  5.]],

        [[ 6.,  7.,  8.]],

        [[ 9., 10., 11.]]])
torch.Size([4, 1, 3])

2. 스퀴즈

  • 차원이 1인 경우 해당 차원을 제거
ft = torch.FloatTensor([[0], [1], [2]])
print(ft)
print(ft.shape)
tensor([[0.],
        [1.],
        [2.]])
torch.Size([3, 1])
print(ft.squeeze())
print(ft.squeeze().shape)
tensor([0., 1., 2.])
torch.Size([3])

언스퀴즈

ft = torch.Tensor([0, 1, 2])
print(ft.shape)
torch.Size([3])
# 숫자 0을 인자로 넣으면 첫번째 차원에 1인 차원이 추가됩니다.

print(ft.unsqueeze(0)) # 인덱스가 0부터 시작하므로 0은 첫번째 차원을 의미한다.
print(ft.unsqueeze(0).shape)
tensor([[0., 1., 2.]])
torch.Size([1, 3])
# 뷰로도 구현 가능 (첫번째 차원을 1로 설정)
print(ft.view(1, -1))
print(ft.view(1, -1).shape)
tensor([[0., 1., 2.]])
torch.Size([1, 3])
# 언스퀴즈에 인자 1을 넣는 경우 (두번째 차원에 1을 추가)
print(ft.unsqueeze(1))
print(ft.unsqueeze(1).shape)
tensor([[0.],
        [1.],
        [2.]])
torch.Size([3, 1])
# 언스퀴즈에 인자 -1을 넣는 경우 (마지막 차원에 1인 차원 추가)
print(ft.unsqueeze(-1))
print(ft.unsqueeze(-1).shape) # 1을 넣는 경우와 결과가 동일
tensor([[0.],
        [1.],
        [2.]])
torch.Size([3, 1])

3. 타입 캐스팅

lt = torch.LongTensor([1, 2, 3, 4])
print(lt) # long 타입
tensor([1, 2, 3, 4])
print(lt.float()) # float 타입
tensor([1., 2., 3., 4.])
bt = torch.ByteTensor([True, False, False, True])
print(bt) #byte 타입 
tensor([1, 0, 0, 1], dtype=torch.uint8)
print(bt.long())
print(bt.float())
tensor([1, 0, 0, 1])
tensor([1., 0., 0., 1.])

4. 연결하기

x = torch.FloatTensor([[1, 2], [3, 4]])
y = torch.FloatTensor([[5, 6], [7, 8]])
print(torch.cat([x, y], dim=0)) # cat 을 통해 연결
tensor([[1., 2.],
        [3., 4.],
        [5., 6.],
        [7., 8.]])
print(torch.cat([x, y], dim=1)) # dim을 0으로
tensor([[1., 2., 5., 6.],
        [3., 4., 7., 8.]])

5. 스택킹 (쌓기)

x = torch.FloatTensor([1, 4])
y = torch.FloatTensor([2, 5])
z = torch.FloatTensor([3, 6])
print(torch.stack([x, y, z]))
tensor([[1., 4.],
        [2., 5.],
        [3., 6.]])
print(torch.stack([x, y, z], dim=1))
tensor([[1., 2., 3.],
        [4., 5., 6.]])

6. ones_like와 zeros_like

  • 1 또는 0으로 채워진 텐서
x = torch.FloatTensor([[0, 1, 2], [2, 1, 0]])
print(x)
tensor([[0., 1., 2.],
        [2., 1., 0.]])
print(torch.ones_like(x)) # 입력 텐서와 크기를 동일하게 하면서 값을 1로 채우기
tensor([[1., 1., 1.],
        [1., 1., 1.]])
print(torch.zeros_like(x)) # 입력 텐서와 크기를 동일하게 하면서 값을 0으로 채우기
tensor([[0., 0., 0.],
        [0., 0., 0.]])

7. 덮어쓰기 연산

x = torch.FloatTensor([[1, 2], [3, 4]])
print(x.mul(2.)) # 곱하기 2를 수행한 결과를 출력
print(x) # 기존의 값 출력
tensor([[2., 4.],
        [6., 8.]])
tensor([[1., 2.],
        [3., 4.]])
print(x.mul_(2.))  # 곱하기 2를 수행한 결과를 변수 x에 값을 저장하면서 결과를 출력
print(x) # 덮어쓴 값 출력
tensor([[2., 4.],
        [6., 8.]])
tensor([[2., 4.],
        [6., 8.]])
profile
Data & PM

0개의 댓글