<강의의 모든 부분을 정리하기 보다는 공부하면서 새롭게 알게된 것과 중요한 부분을 정리하겠습니다.>
Matrix, Tensor
2D Tensor (Matrix) - 일반적으로 이용하는 데이터 형태(batch size, dim)
- 3D Tensor - Vision (batch size, width, height)와 NLP(batch size, length, dim)에서 주로 사용하는 데이터 형태
Tensor Manipulation
본격적으로 Pytorch에서 자주 사용하는 명령어를 살펴 보도록 하겠습니다. Pytorch의 명령어는 Numpy와 매우 유사하다.
Broadcasting Rule
- 계산하는 Tensor의 shape가 달라도 shape을 맞춰 자동으로 계산하여
연산. - 자동으로 실행되기 때문에 주의해야 한다.
- 계산하는 Tensor의 shape가 달라도 shape을 맞춰 자동으로 계산하여
IN [1] :
m1 = torch.FloatTensor(([1, 2]))m2 = torch.FloatTensor([3])print (m1 + m2)
OUT[1]:
tensor([[4.,5.]])
> Broadcasting Rule에 의해 m2(1 * 1) -> (1 * 2) 형태로 변환되어 계산되는 것을 알 수 있다.
> [1, 2] + [3, 3] = [4, 5]
IN [2] :
m3 = torch.FloatTensor(([1, 2]))m4 = torch.FloatTensor([3],[4])print(m3 + m4)
OUT[2] :
tensor([[4., 5.][5., 6.]])
> m3 (1 * 2) -> (2 * 2), m4 (2 * 1) -> (2 * 2) 으로 Broadcasting Rule에 의해 계산시 변환이 된다.
> ([[1, 2], [1, 2] ]) + ([[3, 3], [4, 4]])
Matrix Multiplication vs Multiplication
IN[3] :
m1 = torch.FloatTensor([[1, 2], [3, 4]])m2 = torch.FloatTensor([[1],[2]])print(m1.matmul(m2))
OUT[3] :
tensor([[ 5.],[11.]])
> matmul()은 행렬간의 내적값으로 구해진다.
IN[4] :
m1 = torch.FloatTensor([[1, 2], [3, 4]])m2 = torch.FloatTensor([[1],[2]])print(m1 * m2)print(m1.mul(m2))
OUT[4] :
tensor([[1., 2.],[6., 8.]])tensor([[1., 2.],[6., 8.]])
> mul과 * 는 element wise 곱으로 구해진다.
Mean
IN[5] :
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))
OUT[5] :
tensor(2.5000)tensor([2., 3.])tensor([1.5000, 3.5000])tensor([1.5000, 3.5000])
> 첫 번째 결과는 전체 값의 평균이다. (1+2+3+4) / 4 = 2.5
> 두 번째 결과는 x축 기준의 평균이다. (1+3) / 2 = 2, (2+4) / 2 = 3
> 세 번째 결과는 y축 기준의 평균이다. (1+2) / 2 = 1.5, (3+4) / 2= 3.5
> 네 번째 결과는 마지막에서 첫 번째 축 (y축 기준)값의 평균이다.
Sum
IN[6] :
t = torch.FloatTensor([[1, 2],[3, 4]])print(t.sum())print(t.sum(dim=0))print(t.sum(dim=1))print(t.sum(dim=-1))
OUT[6] :
tensor(10.)tensor([4., 6.])tensor([3., 7.])tensor([3., 7.])
> 첫 번째 결과는 전체 값의 합이다. (1+2+3+4) = 10
> 두 번째 결과는 x축 기준의 평균이다. (1+3) = 4 , (2+4) = 6
> 세 번째 결과는 y축 기준의 평균이다. (1+2) =3, (3+4) = 7
> 네 번째 결과는 마지막에서 첫 번째 축 (y축 기준)값의 평균이다.
Max and Argmax
IN[7] :
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])
OUT[7] :
tensor(4.)torch.return_types.max(values=tensor([3., 4.]),indices=tensor([1, 1]))max: tensor([3., 4.])Argmax: tensor([1, 1])
> max() 명령어는 최대값과, 최대값의 index값을 산출한다.
Squeeze
IN[8] :
ft = torch.FloatTensor(([0],[1],[2]))print(ft.squeeze(dim=0))print((ft.squeeze(dim=0)).shape)print(ft.squeeze(dim=1))print((ft.squeeze(dim=1)).shape)
OUT[8] :
tensor([[0.],[1.],[2.]])torch.Size([3, 1])tensor([0., 1., 2.])torch.Size([3])
> 축의 방향에 따라서 1-dimension 차원 축소
Unsqueeze
IN[9] :
ft = torch.FloatTensor(([0],[1],[2]))print(ft.squeeze(dim=0))print((ft.squeeze(dim=0)).shape)print(ft.squeeze(dim=1))print((ft.squeeze(dim=1)).shape)
OUT[9] :
tensor([[0., 1., 2.]])torch.Size([1, 3]tensor([[0.],[1.],[2.]])torch.Size([3, 1])
> 축의 방향에 따라서 1-dimension 차원 증가
View
IN[10] :
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]))print(ft.view([-1, 3]).shape)print(ft.view([-1, 1, 3]))print(ft.view([-1, 1, 3]).shape)
OUT[10] :
torch.Size([2, 2, 3])tensor([[ 0., 1., 2.],[ 3., 4., 5.],[ 6., 7., 8.],[ 9., 10., 11.]])torch.Size([4, 3])tensor([[[ 0., 1., 2.]],[[ 3., 4., 5.]],[[ 6., 7., 8.]],[[ 9., 10., 11.]]])torch.Size([4, 1, 3])
> Numpy에서 Reshape과 같은 역할을 한다.
> -1은 데이터의 형태에 따라 달라지는 임의의 값을 의미, 위의 예에선 [2 * 2 , 3] = [4, 3]으로 Size조정
Stacking
IN[11] :
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))
OUT[11] :
tensor([[1., 4.],[2., 5.],[3., 6.]])tensor([[1., 2., 3.],[4., 5., 6.]])
> concatenate보다 과정이 더 간소하다. concat을 이용한 방법은 unsqueeze을 이용해서 차원을 맞춰주고 concat을 진행, 복잡하다...
torch.cat([x.unsqueeze(0), y.unsqueeze(0), z.unsqueeze(0)], dim=0)
torch.cat([x.unsqueeze(1), y.unsqueeze(1), z.unsqueeze(1)], dim=1)
참고링크 :
[PyTorch] Lab-01-1 Tensor Manipulation 1
[PyTorch] Lab-01-2 Tensor Manipulation 2
공부하는 시간보다..Markdown으로 정리하는 시간이 오래 걸렸다.. 그래도 Typora도 처음 사용해보고 잼있는듯 앞으로 화이팅 ㅎㅎ