1-1. torch(파이토치 기본)

Author

이상민

Published

March 25, 2025

1.import

import torch

2.기초 지식

- 선형대수학

  • 벡터와 행렬
  • 행렬의 곱셉
  • 트랜스포즈

- 기초통계학(수리통계)

  • 정규분포, 이항분포
  • 모수, 추정
  • \(X_i \overset{i.i.d.}{\sim} N(0,1)\)

- 회귀분석

  • 독립변수(\(y\)), 설명변수(\(X\))
  • \({\boldsymbol y} = {\bf X}{\boldsymbol \beta} + {\boldsymbol \epsilon}\)

- 파이썬

  • 파이썬 기본문법
  • 넘파이, 판다스
  • 전반적인 클래스 지식 (__init__, self, …)
  • 상속

3. torch

A.벡터

torch.tensor([1,2,3])
tensor([1, 2, 3])

- 벡터끼리 덧셈

torch.tensor([1,2,3]) + torch.tensor([3,3,3])
tensor([4, 5, 6])

- 브로드캐스팅 가능 -> 위에와 똑같은 기능

torch.tensor([1,2,3])+2
tensor([3, 4, 5])
torch.tensor([1,2,3])+torch.tensor([2])
tensor([3, 4, 5])
torch.tensor([1,2,3])+torch.tensor(2)
tensor([3, 4, 5])

B. 벡터와 매트릭스

- 3x2 matrix

torch.tensor([[1,2],[3,4],[5,6]])
tensor([[1, 2],
        [3, 4],
        [5, 6]])

- 3X1 matrix 는 3X1 열벡터(column vector)와 같음

torch.tensor([[1],[2],[3]]) 
tensor([[1],
        [2],
        [3]])

- 1X2 matrix 는 1X2 행벡터(row vector)와 같음

torch.tensor([[1,2]]) 
tensor([[1, 2]])

c. matrix 덧셈

- 브로드캐스팅(숫자하나)

torch.tensor([[1,2],[3,4],[5,6]]) - 1
tensor([[0, 1],
        [2, 3],
        [4, 5]])

- 아래와 같은 의미임

torch.tensor([[1,2],[3,4],[5,6]]) - torch.tensor([[1,1],[1,1],[1,1]])
tensor([[0, 1],
        [2, 3],
        [4, 5]])

- 브로드캐스팅(열)

torch.tensor([[1,2],[3,4],[5,6]]) + torch.tensor([[-1],[-3],[-5]])
tensor([[0, 1],
        [0, 1],
        [0, 1]])

- 아래와 같은 의미임

torch.tensor([[1,2],[3,4],[5,6]]) + torch.tensor([[-1,-1],[-3,-3],[-5,-5]])
tensor([[0, 1],
        [0, 1],
        [0, 1]])

- 브로드캐스팅(행)

torch.tensor([[1,2],[3,4],[5,6]]) + torch.tensor([[-1,-2]])
tensor([[0, 0],
        [2, 2],
        [4, 4]])

- 아래와 같은 의미임

torch.tensor([[1,2],[3,4],[5,6]]) + torch.tensor([[-1,-2],[-1,-2],[-1,-2]])
tensor([[0, 0],
        [2, 2],
        [4, 4]])

잘못된 브로드캐스팅

- 열로 브로드캐스팅 하려면 3X1 행렬이어야하지만 여기는 1X3 행렬

torch.tensor([[1,2],[3,4],[5,6]]) + torch.tensor([[-1,-3,-5]])
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[20], line 1
----> 1 torch.tensor([[1,2],[3,4],[5,6]]) + torch.tensor([[-1,-3,-5]])

RuntimeError: The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 1

- 행으로 브로드캐스팅 하려면 1X2 행렬이어야하지만 여기는 2X1 행렬

torch.tensor([[1,2],[3,4],[5,6]]) + torch.tensor([[-1],[-2]])
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[21], line 1
----> 1 torch.tensor([[1,2],[3,4],[5,6]]) + torch.tensor([[-1],[-2]])

RuntimeError: The size of tensor a (3) must match the size of tensor b (2) at non-singleton dimension 0

그냥 벡터를 넣으면 이상하게 행으로만 브로드캐스팅 됨

torch.tensor([[1,2],[3,4],[5,6]]) + torch.tensor([-1,-2])
tensor([[0, 0],
        [2, 2],
        [4, 4]])

- 열로는 안됨..

torch.tensor([[1,2],[3,4],[5,6]]) + torch.tensor([-1,-3,-5])
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[23], line 1
----> 1 torch.tensor([[1,2],[3,4],[5,6]]) + torch.tensor([-1,-3,-5])

RuntimeError: The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 1

D. 행렬곱

정상적 행렬곱

- (3X2) @ (2X1) = (3X1)

torch.tensor([[1,2],[3,4],[5,6]]) @ torch.tensor([[1],[2]])
tensor([[ 5],
        [11],
        [17]])

- (1X3) @ (3X2) = (1X2)

torch.tensor([[1,2,3]]) @ torch.tensor([[1,2],[3,4],[5,6]]) 
tensor([[22, 28]])

잘못된 행렬곱

- (3X2) @ (1X2) = (???)

torch.tensor([[1,2],[3,4],[5,6]]) @ torch.tensor([[1,2]])
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[26], line 1
----> 1 torch.tensor([[1,2],[3,4],[5,6]]) @ torch.tensor([[1,2]])

RuntimeError: mat1 and mat2 shapes cannot be multiplied (3x2 and 1x2)

- (3X1) @ (3X2) = (???)

torch.tensor([[1],[2],[3]]) @ torch.tensor([[1,2],[3,4],[5,6]]) 
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[27], line 1
----> 1 torch.tensor([[1],[2],[3]]) @ torch.tensor([[1,2],[3,4],[5,6]]) 

RuntimeError: mat1 and mat2 shapes cannot be multiplied (3x1 and 3x2)

이상하게 되는 것

- (3X2) @ 행벡터(1X2)->(2X1)행렬로 바꿔주는듯 = (3X1) 행렬이 아닌 (1X3)행벡터로 나옴

torch.tensor([[1,2],[3,4],[5,6]]) @ torch.tensor([1,2])
tensor([ 5, 11, 17])

- 행벡터(1X3) @ (3X2) = (1X2)

torch.tensor([1,2,3]) @ torch.tensor([[1,2],[3,4],[5,6]])
tensor([22, 28])

E. Transpose

- 정방행렬 전치

torch.tensor([[1,2],[3,4]]).T 
tensor([[1, 3],
        [2, 4]])

- (NX1) 행렬 전치

torch.tensor([[1],[3]]).T 
tensor([[1, 3]])

- (1XN) 행렬 전치

torch.tensor([[1,2]]).T 
tensor([[1],
        [2]])

F. reshape

- 일반적인 사용

torch.tensor([[1,2],[3,4],[5,6]]).reshape(2,3)
tensor([[1, 2, 3],
        [4, 5, 6]])

- Transpose와는 다르게 순서대로 reshape 해줌

torch.tensor([[1,2],[3,4],[5,6]]).reshape(6,1)
tensor([[1],
        [2],
        [3],
        [4],
        [5],
        [6]])
torch.tensor([[1,2],[3,4],[5,6]]).reshape(1,6)
tensor([[1, 2, 3, 4, 5, 6]])

- 차원 줄이기도 가능

torch.tensor([[1,2],[3,4],[5,6]]).reshape(6)
tensor([1, 2, 3, 4, 5, 6])

- -1로 설정한 부분은 자동으로 지정됨

torch.tensor([[1,2],[3,4],[5,6]]).reshape(2,-1)
tensor([[1, 2, 3],
        [4, 5, 6]])
torch.tensor([[1,2],[3,4],[5,6]]).reshape(-1,6)
tensor([[1, 2, 3, 4, 5, 6]])

- -1만 넣으면 행벡터로 만들어버림

torch.tensor([[1,2],[3,4],[5,6]]).reshape(-1)
tensor([1, 2, 3, 4, 5, 6])
torch.tensor([[[1,2],[2,30]],[[1,2],[3,3]]]).reshape(-1)
tensor([ 1,  2,  2, 30,  1,  2,  3,  3])

G. concat, stack (★★★)

- concat

  • axis=0 인 경우 0번째 차원을 기준으로 합쳐짐
  • axis=1 인 경우 1번째 차원을 기준으로 합쳐짐
a = torch.tensor([[1],[3],[5]])
b = torch.tensor([[2],[4],[6]])
torch.concat([a,b],axis=0)
tensor([[1],
        [3],
        [5],
        [2],
        [4],
        [6]])
a = torch.tensor([[1],[3],[5]])
b = torch.tensor([[2],[4],[6]])
torch.concat([a,b],axis=1)
tensor([[1, 2],
        [3, 4],
        [5, 6]])

- stack

  • axis=0 : 0번째 차원을 추가
  • axis=1 : 1번째 차원을 추가
a = torch.tensor([1,3,5])
b = torch.tensor([2,4,6])
torch.stack([a,b],axis=1)
tensor([[1, 2],
        [3, 4],
        [5, 6]])