Pytorch example code#

예제 코드 실행해보기#

아래 예제 코드를 현재 환경에서 실행시켜봅시다.

# -*- coding: utf-8 -*-
import numpy as np
import math

# 무작위로 입력과 출력 데이터를 생성합니다
x = np.linspace(-math.pi, math.pi, 2000)
y = np.sin(x)

# 무작위로 가중치를 초기화합니다
a = np.random.randn()
b = np.random.randn()
c = np.random.randn()
d = np.random.randn()

learning_rate = 1e-6
for t in range(2000):
    # 순전파 단계: 예측값 y를 계산합니다
    # y = a + b x + c x^2 + d x^3
    y_pred = a + b * x + c * x ** 2 + d * x ** 3

    # 손실(loss)을 계산하고 출력합니다
    loss = np.square(y_pred - y).sum()
    if t % 100 == 99:
        print(t, loss)

    # 손실에 따른 a, b, c, d의 변화도(gradient)를 계산하고 역전파합니다.
    grad_y_pred = 2.0 * (y_pred - y)
    grad_a = grad_y_pred.sum()
    grad_b = (grad_y_pred * x).sum()
    grad_c = (grad_y_pred * x ** 2).sum()
    grad_d = (grad_y_pred * x ** 3).sum()

    # 가중치를 갱신합니다.
    a -= learning_rate * grad_a
    b -= learning_rate * grad_b
    c -= learning_rate * grad_c
    d -= learning_rate * grad_d

print(f'Result: y = {a} + {b} x + {c} x^2 + {d} x^3')

예상되는 결과#

  1. Python 미설치

    bash: python: command not found
    
  2. NumPy 미설치

    Traceback (most recent call last):
    File "example.py", line 1, in <module>
        import numpy as np
    ModuleNotFoundError: No module named 'numpy'
    
  3. 코드 실행

    Step 100  loss: 1234.56
    Step 200  loss: 789.01
    …
    최종 모델: y = 0.0012 + 1.0003 x + 

이처럼 환경 차이로 인해 같은 코드를 실행해도 전혀 다른 결과가 나타날 수 있습니다.
이런 예기치 못한 문제를 방지하려면, 동일한 실행 환경을 갖춰야 합니다.

Ref.#

PyTorch Tutorials “PyTorch with Examples”, https://tutorials.pytorch.kr/beginner/pytorch_with_examples.html