ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Pythrch | 기초
    Deep Learning/PyTorch 2021. 6. 1. 22:01
    728x90

    Basic

    Tensor

    파이토치를 이용해 텐서의 차원을 다루어보자

    import torch
    
    
    def print_description(x):
        print(x)
        print(f'Size:{x.size()}')
        print(f'Shape:{x.shape}')
        print(f'dimension:{x.ndimension()}')
        print()
    
    
    # make tensor and print description
    x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    print_description(x)
    
    # 랭크 늘리기
    x = torch.unsqueeze(x, 0)
    print_description(x)
    
    # 랭크 줄이기
    x = torch.squeeze(x)
    print_description(x)
    
    # view
    x = x.view(9)
    print_description(x)
    

     

    tensor()

    텐서를 만든다.

    unsqueeze()

    랭크(dimension)을 늘린다.

    squeeze()

    랭크(dimension)을 줄인다.

    view()

    랭크(dimension)을 원하는 만큼으로 설정한다.

    행렬 곱

    import torch
    
    w = torch.randn(5, 3, dtype=torch.float)
    x = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
    
    print("w size", w.size())
    print("x size", x.size())
    print("w:", w)
    print("x:", x)
    
    b = torch.randn(5, 2, dtype=torch.float)
    print("b size", b.size())
    print("b:", b)
    
    # 행렬 곱
    wx = torch.mm(w, x)
    print("wx size:", wx.size())
    print("wx:", wx)
    
    result = wx + b
    print("result size:", result.size())
    print("result:", result)

    torch.mm() 함수를 이용한다.

    numpy.dot() 이랑 같은 기능인가 보다.

     

    Autograd

    직역하면 "자동기울기"

    미분 계산을 자동화하여 경사하강법을 구현하는 수고를 덜어준다.

    사용해보자.

    import torch
    
    w = torch.tensor(1.0, requires_grad=True)
    a = w * 3
    l = a ** 2
    
    l.backward()
    print(f'l을 w로 미분한 값은 {w.grad}')
    
    l을 w로 미분한 값은 18.0

    requires_gard=True 값을 설정하면 pytorch의 Autograd 기능이 자동으로 계산할 때 w에 대한 미분값을 w.grad에 저장한다.

    변수를 수식으로 표현하면 아래와 같다.

    backward()를 통해 역전파로 미분값을 구한다.

    728x90

    'Deep Learning > PyTorch' 카테고리의 다른 글

    PyTorch | GAN  (4) 2022.01.09
    PyTorch | DNN  (0) 2021.06.20
    Pytorch | ANN  (0) 2021.06.12
    PyTorch | 이미지 복원  (0) 2021.06.04
    PyTorch 설치  (0) 2021.06.01

    댓글

Designed by Tistory.