Tensor Manipulation 1

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

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

기본 setting에서의 2D Tensor 크기 = (batch size, dim)
Computer Vision에서의 3D Tensor 크기 = (batch size, width, height)
자연어 처리에서의 3D Tensor 크기 = (batch size, length, dim)

1D Array with PyTorch

t = torch.FloatTensor([0., 1., 2., 3., 4., 5., 6.])

print(t.dim()) #rank
print(t.shape) #shape (사이즈랑 비슷한 듯)
print(t.size()) #shape
print(t[0], t[1], t[-1]) #Element
print(t[2:5], t[4:-1]) #Slicing
print(t[:2], t[3:]) #Slicing

2D Array with PyTorch

t = torch.FloatTensor([[1., 2., 3.],
                       [4., 5., 6.],
                       [7., 8., 9.],
                       [10., 11., 12.],])
                       print(t.dim())
print(t.size())
print(t[:, 1])
print(t[:, 1].size())
print(t[:, :-1])
>>
2
torch.Size([4, 3])
tensor([ 2.,  5.,  8., 11.])
torch.Size([4])
tensor([[ 1.,  2.],
        [ 4.,  5.],
        [ 7.,  8.],
        [10., 11.]])

Broadcasting

Broadcasting에 대한 더 자세한 내용은 여기
브로드캐스팅의 조건
1) 각 텐서는 최소한 하나의 차원을 가지고 있어야 함
2) 차원 크기만큼 반복할 때에는, 마지막 차원부터 시작하여 ① 차원 크기가 동일하거나, ② 둘 중 하나가 1이거나, ③ 둘 중 하나가 존재하지 않아야 함

# Same shape
m1 = torch.FloatTensor([[3, 3]])
m2 = torch.FloatTensor([[2, 2]])
print(m1 + m2)

# Vector + scallar
m1 = torch.FloatTensor([[1, 2]])
m2 = torch.FloatTensor([[3]])
print(m1 + m2)

# 2*1 Vector + 1*2 Vector
m1 = torch.FloatTensor([[1, 2]])
m2 = torch.FloatTensor([[3], [4]])
print(m1 + m2)
>>
tensor([[5., 5.]])
tensor([[4., 5.]])
tensor([[4., 5.],
        [5., 6.]])

이해한 대로가 맞는지는 모르겠지만

  • Same shape에서는 ①번 조건 만족
    ⇒ Broadcasting 조건 만족
  • Vector + scallar에서는, m1의 차원이 [1, 2]이고 m2 차원이 [1, 1]임
    마지막 차원(아마 끝 차원을 말하는 건가?)이 2 & 1이니까 ②번 조건 만족
    그 이전 차원은 1 & 1이니까 ①번 조건 만족
    ⇒ Broadcasting 조건 만족
  • 2x1 Vector + 2x1 Vector에서는, m1 차원이 [1, 2]이고 m2 차원이 [2, 1]임
    마지막 차원이 2 & 1이니까 ②번 조건 만족
    그 이전 차원은 1 & 2이니까 ②번 조건 만족
    ⇒ Broadcasting 조건 만족

더 자세한 건... 저 위 링크에 torch.empty를 활용한 예제가 있음

Multiplication vs Matrix Multiplication

# Multiplication vs Matrix Multiplication

m1 = torch.FloatTensor([[1, 2], [3, 4]])
m2 = torch.FloatTensor([[1], [2]])
print(m1.matmul(m2)) # 2 * 1, 행렬곱 수행
print(m1.mul(m2)) # 2 * 2, 그냥 각각의 행과 열끼리 곱함
>> 
tensor([[ 5.],
        [11.]])
tensor([[1., 2.],
        [6., 8.]])

Mean

FloatTensor에만 작동함. LongTensor(정수 텐서) 같은 경우 mean 함수가 작동하지 않음!

# Mean

t = torch.FloatTensor([1, 2])
print(t.mean())
t = torch.FloatTensor([[1, 2], [3, 4]])
print(t.mean())
print(t.mean(dim=0)) #첫 번째 차원(가장 바깥쪽 차원?)에 대해서 수행
print(t.mean(dim=1)) #두 번째 차원에 대해서 수행
print(t.mean(dim=-1))
>>
tensor(1.5000)
tensor(2.5000)
tensor([2., 3.])
tensor([1.5000, 3.5000])
tensor([1.5000, 3.5000])

Sum

Mean과 동일하게 작동함

Max and Argmax

Max는 가장 큰 값을 리턴함. Argmax는 index를 이용하여 접근

# Max and Argmax
t = torch.FloatTensor([[1, 2], [3, 4]])
print(t.max())
print(t.max(dim=0)) #가장 바깥쪽 차원들에 대해서 큰 순서대로 배열하여 출력함
print('Max: ', t.max(dim=0)[0]) #가장 큰 값
print('Argmax: ', t.max(dim=0)[1]) #그 다음으로 큰 값
print(t.max(dim=1)) # = print(t.max(dim=-1))
>>
tensor(4.)
torch.return_types.max(values=tensor([3., 4.]), indices=tensor([1, 1]))
Max:  tensor([3., 4.])
Argmax:  tensor([1, 1])
torch.return_types.max(values=tensor([2., 4.]), indices=tensor([1, 1]))

0개의 댓글