[인공지능] 3주차(실습) | 비용 최소화하기 (Minimizing Cost)

dusruddl2·2022년 10월 16일

SJU_인공지능

목록 보기
9/23

  • H(x)H(x): 주어진 xx값에 대해 예측을 어떻게 할 것인가 - 가설함수 (모델)
  • cost(W)cost(W): H(x)H(x)yy를 얼마나 잘 예측했는가 - 비용함수(비용)

** [주의] 식을 간소화 하기 위해 가설함수에 편향변수 b를 추가히자 않았음.


라이브러리 imports

# 시각화용 라이브러리
import matplotlib.pyplot as plt

import numpy as np
import torch
import torch.optim as optim

학습 데이터 만들기

x_train = torch.FloatTensor([[1], [2], [3]])
y_train = torch.FloatTensor([[1], [2], [3]])
# Data
plt.scatter(x_train, y_train)
# Best-fit line
xs = np.linspace(1, 3, 1000)
plt.plot(xs, xs)

가중치 값의 변화에 따른 비용 값 (Cost by W)

H(x)=WxH(x) = Wx

# -5 ~ 7 사이를 1000등분해서 w_l
# list <= 순차적으로 데이터를 담는 추상자료형

# w_list
W_l = np.linspace(-5, 7, 1000)
# cost list
cost_l = []
for W in W_l:
    hypothesis = W * x_train
    cost = torch.mean((hypothesis - y_train) ** 2)

    cost_l.append(cost.item())
plt.plot(W_l, cost_l)
plt.xlabel('$W$')
plt.ylabel('Cost')
plt.show()

Gradient Descent (유도에 의한 수동미분)

W = 0

gradient를 직접 구현하면 다음과 같음 (2/m은 생략)

gradient = 2*torch.mean((W * x_train - y_train) * x_train)
print(gradient)

lr = 0.1 # lr = learning rate = 알파 (alpha)
W -= lr * gradient # w = w - lr * gradient
print(W)

0이었던 weight값이 1.4로 update된 것을 확인할 수 있었어.


✅ FULL CODE - 1

# 데이터
x_train = torch.FloatTensor([[1],[2],[3]])
y_train = torch.FloatTensor([[1],[2],[3]])

# 모델 초기화
W = torch.zeros(1, requries_grad = True)

# learning rate설정
lr = 0.1

nb_epochs = 10
for epoch in range(nb_epochs+1):
	
    # H(x) 계산
    hypothesis = x_train * W
    
    #cost & gradient 계산
    cost = torch.mean(((hypothesis-y)**2)
    gradient = 2 * torch.mean((hypothesis-y)*x_train)
    
    print('Epoch: {:4d}/{}, W: {:.3f}, b: {:.3f}, Cost: {.6f}'.format(
    epoch, nb_epochs, W.item(), cost.item()
    ))
    
    #cost gradient로 W 개선
    W -= lr * gradient
    
    

requires_grad: default값은 False임

  • feature이 1개이므로 hypothesis 구할 때 mamtul이 아니라 *로 한 것


✅ FULL CODE - 2 (optim 이용)

# 데이터
x_train = torch.FloatTensor([[1],[2],[3]])
y_train = torch.FloatTensor([[1],[2],[3]])

# 모델 초기화
W = torch.zeros(1, requries_grad = True)

#optimizer 설정
optimizer = optim.SGD([W], lr = 0.15)

nb_epochs = 10
for epoch in range(nb_epochs + 1):

	# H(x) 계산
    hypothesis = x_train * W
    
    # cost 계산
    cost = torch.mean((hypothesis-y_train)**2)
    
    print('Epoch: {:4d}/{}, W: {:.3f}, b: {:.3f}, Cost: {:.6f}'.format(
    epoch, nb_epochs, W.item(), b.item(), cost.item()
    ))
    
    #optimizer 초기화
    optimizer.zero_grad()
    #cost계산
    cost.backward()
    #optimzier 갱신
    optimizer.step()
    

profile
정리된 글은 https://dusruddl2.tistory.com/로 이동

0개의 댓글