Tensor Manipulation 2

오늘 날씨는 야옹·2023년 5월 6일

파이토치로 시작하는 딥러닝 기초 (부스트코스) - Lab-01-2 Tensor Manipulation 2

View (Reshape)

차원을 변형한다
-1을 넣으면
이 차원이 몇인진 잘 모르겠고 알아서 차원 좀 넣어 줘 ㅎㅎ
같은 의미

t = np.array([[[0, 1, 2],
              [3, 4, 5]],

              [[6, 7, 8],
               [9, 10, 11]]])
ft = torch.FloatTensor(t)
print(ft.shape)
print(ft.view([-1, 3]).shape)
print(ft.view([-1, 1, 3]).shape)
>>
torch.Size([2, 2, 3])
torch.Size([4, 3])
torch.Size([4, 1, 3])

Squeeze

View 함수를 사용한 것과 같은데, 자동으로 1인 차원을 없앰

ft = torch.FloatTensor([[0], [1], [2]])
print(ft.shape)
print(ft.squeeze().shape)
>>
torch.Size([3, 1])
torch.Size([3])

만약에 squeeze(dim=i)를 하면, i번째 dimension이 1인 경우에 squeeze해 준다.
위의 경우에는 squeeze(dim=0)을 해도 0번째 dimension이 3이기 때문에 같은 결과를 출력한다.
그러나 squeeze(dim=1)을 하면 torch.Size([3])이 나오겠지

Unsqueeze

원하는 Dimension에 1을 넣어 줌
그렇기 때문에 dimension을 꼭 명시해 줘야 한다

ft = torch.FloatTensor([0, 1, 2])
print(ft.shape)
print(ft.unsqueeze(0).shape)
print(ft.unsqueeze(1).shape) # = ft.unsqueeze(-1).shape
>>
torch.Size([3])
torch.Size([1, 3])
torch.Size([3, 1])

Concatenate

이어붙이는 함수 cat? 고양이?

x = torch.FloatTensor([[1, 2], [3, 4]])
y = torch.FloatTensor([[5, 6], [7, 8]])
print(torch.cat([x, y], dim=0))
print(torch.cat([x, y], dim=1))
>>
tensor([[1., 2.],
        [3., 4.],
        [5., 6.],
        [7., 8.]])
tensor([[1., 2., 5., 6.],
        [3., 4., 7., 8.]])

2x2 텐서를 dim=0에 대해서 두 개를 연결함 => 4x2
2x2 텐서를 dim=1에 대해서 두 개를 연결함 => 2x4

Stacking

Concatenate를 좀 더 편리하게 이용하도록 몇 가지 기능들을 단축시킨 것

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

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

1x2 텐서를 dim=0에 대해서 세 개를 쌓음 => 3x2
1x2 텐서를 dim=1에 대해서 세 개를 쌓음 => 2x3

Concatenate과 비교하면, 무언가 unsqueeze가 되었다......

print(torch.stack([x, y, z]))
print(torch.cat([x.unsqueeze(0), y.unsqueeze(0), z.unsqueeze(0)], dim=0))

이 두 개가 같음

Ones and Zeros

x = torch.FloatTensor([[0, 1, 2], [2, 1, 0]])
print(x)
print(torch.ones_like(x)) # x와 같은 사이즈의 1 텐서를 만들어라
print(torch.zeros_like(x)) # x와 같은 사이즈의 0 텐서를 만들어라
>>
tensor([[0., 1., 2.],
        [2., 1., 0.]])
tensor([[1., 1., 1.],
        [1., 1., 1.]])
tensor([[0., 0., 0.],
        [0., 0., 0.]])

In-place Operation

연산한 값을 새로 메모리 공간을 만들지 않고, 연산했던 변수에 그대로 다시 넣음
마치 +=, -= 같은...

x = torch.FloatTensor([[1, 2], [3, 4]])
print(x.mul(2.))
print(x) #값이 바뀌지 않음
print(x.mul_(2.))
print(x) #값이 바뀜
>>
tensor([[2., 4.],
        [6., 8.]])
tensor([[1., 2.],
        [3., 4.]])
tensor([[2., 4.],
        [6., 8.]])
tensor([[2., 4.],
        [6., 8.]])

0개의 댓글