가중치가 2개이고 이차함수 형태인 비선형 모델에 대해 Gradient Descent 알고리즘으로 머신러닝 구현
- loss를 w1, w2에 대해 편미분하였다.
- 기존 마지막 데이터 포인트값에 대해 스칼라값으로 loss를 출력하던걸, 한 개 epoch에서 loss를 평균하여 출력하도록 개선하였다.
#exercise 3-1 compute gradint, 모델의 가중치가 2개인 경우 -> implement machine learning
import numpy as np
import matplotlib.pyplot as plt
w1 = 1.0 #가중치 랜덤값으로 시작
w2 = 1.0 #가중치 랜덤값으로 시작
b = 0.0 #biased
x_data = [1.0,2.0,3.0]
y_data = [2.0,4.0,6.0]
running_rate = 0.01
def forward(x) :
return x*x*w2 + x*w1 + b
def loss(x,y):
y_pred = forward(x)
return (y_pred - y)*(y_pred-y)
def gradient_1(x,y): # d_loss / d_w1
return 2 * x * (x*x*w2 + x*w1 + b - y)
def gradient_2(x,y) : #d_loss / d_w2
return 2 * x * x * (x*x*w2 + x*w1 + b - y)
print("학습하기 전 예측값 공부시간 4시간 시험점수는 ? ", forward(4))
for epoch in range(100) :
loss_total = 0 # 변수 초기화
for i , x_val in enumerate(x_data):
y_val = y_data[i]
w1 = w1 - running_rate * gradient_1(x_val,y_val)
w2 = w2 - running_rate * gradient_2(x_val,y_val)
l = loss(x_val,y_val)
loss_total += l
print("\t x_val y_val ", x_val, y_val, " grad " ,gradient_1(x_val,y_val), gradient_2(x_val,y_val) )
print("epoch", epoch , "w1 " , w1 , "w2", w2 , "mean of loss", loss_total / len(x_data))
print("학습 후 예측값 공부시간 4시간 시험점수는 ? ", forward(4))'vision,deep learning > PyTorchZeroToAll (in English) Review' 카테고리의 다른 글
| PyTorch Zero To All - 05 Linear Regression in the PyTorch way Review (1) | 2025.05.12 |
|---|---|
| PyTorch Zero To All - 04 Back-propagation and Autograd Review (0) | 2025.05.11 |
| PyTorch Zero To All - 03 Gradient Descent Review (0) | 2025.05.08 |
| PyTorch Zero To All - 02 Linear Model Review (0) | 2025.05.08 |
| PyTorch Zero To All Lecture Review 시작 (0) | 2025.05.07 |