[ 머신러닝 ] 파이토치

2023. 9. 11. 19:03머신러닝

728x90

1. 파이토치(Pytorch)

  • 텐서플로우와 함께 머신러닝, 딥러닝에서 가장 널리 사용되는 프레임워크
  • 초기에는 Torch라는 이름으로 Lua언어 기반으로 만들어졌으나, 파이썬 기반으로 변경한 것이 Pytorch
  • 뉴욕대학교와 페이스북이 공동으로 개발하였고, 현재 가장 대중적이고 널리 사용됨
import torch
print(torch.__version__)
--------------------------
# 결과
2.0.1+cu118
--------------------------

1-1. 스칼라(Scalar)

  • 하나의 상수를 의미
var1 = torch.tensor([1])

type(var1)
-------------------------
# 결과
torch.Tensor
-----------------------------
var2 = torch.tensor([6.5])

# 두 스칼라의 사칙 연산
print(var1 + var2)
print(var1 - var2)
print(var1 * var2)
print(var1 / var2)
-----------------------------
# 결과
tensor([7.5000])
tensor([-5.5000])
tensor([6.5000])
tensor([0.1538])
-----------------------------

1-2. 벡터(Vector)

  • 상수가 두 개 이상 나열되었을 경우
vec1 = torch.tensor([1, 2, 3])
vec1
-------------------------------
# 결과
tensor([1, 2, 3])

--------------------------------
type(vec1)
--------------------------------
# 결과
torch.Tensor

-----------------------------------
vec2 = torch.tensor([10, 20, 30])

# 두 벡터의 사칙 연산
print(vec1 + vec2)
print(vec1 - vec2)
print(vec1 * vec2)
print(vec1 / vec2)
-----------------------------------
# 결과
tensor([11, 22, 33])
tensor([ -9, -18, -27])
tensor([10, 40, 90])
tensor([0.1000, 0.1000, 0.1000])

-------------------------------------

1-3. 행렬(Matrix)

  • 2개 이상의 벡터 값을 가지고 만들어진 값으로 행과 열의 개념을 가진 숫자의 나열
mat1 = torch.tensor([[1,2], [3,4]])
print(mat1)
--------------------------------------
# 결과
tensor([[1, 2],
        [3, 4]])
        
--------------------------------------
mat2 = torch.tensor([[7,8], [9,10]])
print(mat2)
--------------------------------------
# 결과
tensor([[ 7,  8],
        [ 9, 10]])
        
--------------------------------------
# 두 행렬의 사칙 연산
print(mat1 + mat2)
print(mat1 - mat2)
print(mat1 * mat2)
print(mat1 / mat2)
--------------------------------------
# 결과
tensor([[ 8, 10],
        [12, 14]])
tensor([[-6, -6],
        [-6, -6]])
tensor([[ 7, 16],
        [27, 40]])
tensor([[0.1429, 0.2500],
        [0.3333, 0.4000]])
        
--------------------------------------

1-4. 텐서(Tensor)

  • 다수의 행렬이 모이면 텐서라고 부름
  • 배열이나 행렬과 매우 유사한 특수한 자료구조
  • 파이토치는 텐서를 사용하여 모델의 입력과 출력, 모델의 매개변수들을 처리 사용됨
from IPython.display import Image
Image(url='https://miro.medium.com/max/875/1*jRyyMAhS_NZxqyv3EoLCvg.png')

tensor1 = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(tensor1)
------------------------------------------------------------
# 결과
tensor([[[1, 2],
         [3, 4]],

        [[5, 6],
         [7, 8]]])
         
---------------------------------------------------------------
tensor2 = torch.tensor([[[9, 10], [11, 12]], [[13, 14], [15, 16]]])
print(tensor2)
--------------------------------------------------------------------
# 결과
tensor([[[ 9, 10],
         [11, 12]],

        [[13, 14],
         [15, 16]]])
         
---------------------------------------------------------------------
print(tensor1 + tensor2)
print(tensor1 - tensor2)
print(tensor1 * tensor2)
print(tensor1 / tensor2)
---------------------------------------------------------------------
# 결과
tensor([[[10, 12],
         [14, 16]],

        [[18, 20],
         [22, 24]]])
tensor([[[-8, -8],
         [-8, -8]],

        [[-8, -8],
         [-8, -8]]])
tensor([[[  9,  20],
         [ 33,  48]],

        [[ 65,  84],
         [105, 128]]])
tensor([[[0.1111, 0.2000],
         [0.2727, 0.3333]],

        [[0.3846, 0.4286],
         [0.4667, 0.5000]]])

------------------------------------------------------------------------
print(torch.add(tensor1,tensor2))
print(torch.subtract(tensor1,tensor2))
print(torch.multiply(tensor1,tensor2))
print(torch.divide(tensor1,tensor2))
print(torch.matmul(tensor1,tensor2)) # 행렬곱 연산
------------------------------------------------------------------------
# 결과
tensor([[[10, 12],
         [14, 16]],

        [[18, 20],
         [22, 24]]])
tensor([[[-8, -8],
         [-8, -8]],

        [[-8, -8],
         [-8, -8]]])
tensor([[[  9,  20],
         [ 33,  48]],

        [[ 65,  84],
         [105, 128]]])
tensor([[[0.1111, 0.2000],
         [0.2727, 0.3333]],

        [[0.3846, 0.4286],
         [0.4667, 0.5000]]])
tensor([[[ 31,  34],
         [ 71,  78]],

        [[155, 166],
         [211, 226]]])
         
-----------------------------------------------------------------------------
print(tensor1.add_(tensor2)) # tensor1에 결과를 다시 저장, 모든 사칙 연산자에 _ 를 붙여 사용할 수 있음
print(tensor1)
-------------------------------------------------------------------------------------------------
# 결과
tensor([[[19, 22],
         [25, 28]],

        [[31, 34],
         [37, 40]]])
tensor([[[19, 22],
         [25, 28]],

        [[31, 34],
         [37, 40]]])
         
--------------------------------------------------------------------------------------------------

2. 텐서의 변환

data = [[1,2], [3,4]]
print(data)
------------------------------
# 결과
[[1, 2], [3, 4]]

------------------------------
x_data = torch.tensor(data)
print(x_data)
------------------------------
# 결과
tensor([[1, 2],
        [3, 4]])
        
------------------------------
import numpy as np

np_arr = np.array(data)
np_arr
------------------------------
# 결과
array([[1, 2],
       [3, 4]])
------------------------------
x_np_1 = torch.tensor(np_arr)
x_np_1
------------------------------
# 결과
tensor([[1, 2],
        [3, 4]])
        
------------------------------
x_np_1[0, 0] = 100
print(x_np_1)
print(np_arr)
------------------------------
# 결과
tensor([[100,   2],
        [  3,   4]])
[[1 2]
 [3 4]]

------------------------------
x_np_2 = torch.as_tensor(np_arr) # ndarray와 동일한 메모리 주소를 가리키는 뷰를 만드는 함수
print(x_np_2)
---------------------------------------------------------------------------------------
# 결과
tensor([[1, 2],
        [3, 4]])
        
---------------------------------------------------------------------------------------
x_np_2[0, 0] = 200 # 기존 메모리 주소의 ndarray 값을 변경하게 됨
print(x_np_2)
print(np_arr)
---------------------------------------------------------------------------------------
# 결과
tensor([[200,   2],
        [  3,   4]])
[[200   2]
 [  3   4]]

----------------------------------------------------------------------------------------

x_np_3 = torch.from_numpy(np_arr) # ndarray와 동일한 메모리 주소를 가리키는 뷰를 만드는 함수
print(x_np_3)
x_np_3[0, 0] = 400 # 기존 메모리 주소의 ndarray 값을 변경하게 됨
print(x_np_3)
print(np_arr)
-----------------------------------------------------------------------------------------
# 결과
tensor([[200,   2],
        [  3,   4]])
tensor([[400,   2],
        [  3,   4]])
[[400   2]
 [  3   4]]
 
------------------------------------------------------------------------------------------
np_again = x_np_1.numpy()
print(np_again, type(np_again))
------------------------------------------------------------------------------------------
# 결과
[[100   2]
 [  3   4]] <class 'numpy.ndarray'>
 
------------------------------------------------------------------------------------------

3. 파이토치 주요 함수

a = torch.ones(2, 3)
print(a)
--------------------------
# 결과
tensor([[1., 1., 1.],
        [1., 1., 1.]])
        
---------------------------
b = torch.zeros(2, 3)
print(b)
---------------------------
# 결과
tensor([[0., 0., 0.],
        [0., 0., 0.]])
        
---------------------------
c = torch.full((2,3), 10)
print(c)
---------------------------
# 결과
tensor([[10, 10, 10],
        [10, 10, 10]])
        
----------------------------
d = torch.empty(2,3) # 실수 무작위값을 넣어줌
print(d)
--------------------------------------------
# 결과
tensor([[6.1371e+01, 4.5863e-41, 6.6741e-34],
        [0.0000e+00, 4.4842e-44, 0.0000e+00]])

-----------------------------------------------
e = torch.eye(5)
print(e)
-----------------------------------------------
# 결과
tensor([[1., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0.],
        [0., 0., 1., 0., 0.],
        [0., 0., 0., 1., 0.],
        [0., 0., 0., 0., 1.]])

------------------------------------------------
f = torch.arange(10)
print(f)
------------------------------------------------
# 결과
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

------------------------------------------------
g = torch.rand(2, 3) # 랜덤한 숫자를 나열해줌, 0~1 사이의 양수만 출력
print(g)
-------------------------------------------------------------------
# 결과
tensor([[0.6946, 0.9958, 0.2823],
        [0.2633, 0.7510, 0.9999]])
        
--------------------------------------------------------------------
h = torch.randn(2, 3) # 평균이 0이고 표준편차가 1인 정규 분포에서 난수로 이루어진 텐서
print(h)
----------------------------------------------------------------------------------
# 결과
tensor([[-0.8430,  0.1209, -0.3566],
        [-0.1346, -0.5230, -0.1830]])
-----------------------------------------------------------------------------------
i = torch.arange(16).reshape(2, 2, 4) # 0, 1, 2번이라고 생각
print(i, i.shape)

# 차원을 인덱스로 변경
j = i.transpose(1, 2) # 1, 2번이 들어옴 # 2, 4, 2
print(j, j.shape)
------------------------------------------------------------------------------------
# 결과
tensor([[[ 0,  1,  2,  3],
         [ 4,  5,  6,  7]],

        [[ 8,  9, 10, 11],
         [12, 13, 14, 15]]]) torch.Size([2, 2, 4])
tensor([[[ 0,  4],
         [ 1,  5],
         [ 2,  6],
         [ 3,  7]],

        [[ 8, 12],
         [ 9, 13],
         [10, 14],
         [11, 15]]]) torch.Size([2, 4, 2])

-----------------------------------------------------------------------------------
# 차원을 인덱스로 변환
k = i.permute((2, 0, 1)) # 2, 2, 4 -> 4, 2, 2
print(k, k.shape)
------------------------------------------------------------------------------------
# 결과
tensor([[[ 0,  4],
         [ 8, 12]],

        [[ 1,  5],
         [ 9, 13]],

        [[ 2,  6],
         [10, 14]],

        [[ 3,  7],
         [11, 15]]]) torch.Size([4, 2, 2])
         
-------------------------------------------------------------------------------------

4. GPU 사용하기

  • 코랩에서 device 변경하는 방법
    • 상단 메뉴 -> 런타임 -> 런타임 유형변경 -> 하드웨어 가속기를 GPU로 변경 -> 저장 -> 다시 시작 및 모두 실행
ts = torch.rand(3, 4)
print(f'shape: {ts.shape}')
print(f'type: {ts.dtype}')
print(f'device: {ts.device}')
--------------------------------------
# 결과
shape: torch.Size([3, 4])
type: torch.float32
device: cpu

--------------------------------------
ts = ts.reshape(4, 3)
ts = ts.int()
if torch.cuda.is_available():
  print('GPU를 사용할 수 있음')
  ts = ts.to('cuda')

print(f'shape: {ts.shape}')
print(f'type: {ts.dtype}')
print(f'device: {ts.device}')
----------------------------------------
# 결과
GPU를 사용할 수 있음
shape: torch.Size([4, 3])
type: torch.int32
device: cuda:0

-----------------------------------------

5. 텐서의 인덱싱과 슬라이싱

a = torch.arange(1, 13).reshape(3, 4)
print(a)
---------------------------------------
# 결과
tensor([[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]])
       
-----------------------------------------
print(a[1])
print(a[0, -1])
print(a[1:-1])
print(a[:2, 2:])
------------------------------------------
# 결과
tensor([5, 6, 7, 8])
tensor(4)
tensor([[5, 6, 7, 8]])
tensor([[3, 4],
        [7, 8]])
728x90
반응형

'머신러닝' 카테고리의 다른 글

[ 머신러닝 ] KMEans  (0) 2023.09.11
[ 머신러닝 ] lightGBM  (0) 2023.09.11
[ 머신러닝 ] 랜덤 포레스트  (0) 2023.09.11
[ 머신러닝 ] 서포트 벡터 머신  (0) 2023.09.06
[ 머신러닝 ] 로지스틱 회귀  (0) 2023.09.06