[인공지능] 3주차(실습) | 단일선형회귀

dusruddl2·2022년 9월 20일

SJU_인공지능

목록 보기
8/23

비용함수(cost function) 혹은 목적함수(objective function)

import numpy
import torch.optim as optim
# For reproducibility - 매번 실행할때마다 코드의 결과 값을 동일하게 하기 위한 과정
torch.manual_seed(1)

학습 데이터 (Data)

  • 예시를 위해 가짜 데이터를 만들어 사용하겠습니다.
  • 기본적으로 PyTorch의 행렬은 NCHW 형태이다.
# (x1,y1)=(1,1), (x2,y2)=(2,2), (x3,y3)=(3,3)
x_train = torch.FloatTensor([[1], [2], [3]])
y_train = torch.FloatTensor([[1], [2], [3]])

x_train shape 구하기

print(x_train)
print(x_train.shape)

y_train shape 구하기

print(y_train)
print(y_train.shape)


가중치 초기화 (Weight Initialization)

# requires_grad 학습에 사용하겠다는 의미
W = torch.zeros(1, requires_grad=True)
print(W)

# requires_grad 학습에 사용하겠다는 의미
b = torch.zeros(1, requires_grad=True)
print(b)


가설함수(Hypothesis)¶

H(x)=Wx+bH(x) = Wx + b

# 학습 모델에 해당됨
hypothesis = x_train * W + b
print(hypothesis)

비용함수(Cost function)¶

cost = torch.mean((hypothesis - y_train) ** 2)
print(cost)


학습 방법: Gradient Descent

  • 비용함수를 가장 작게 만다는 가중치 W를 찾는 방법, 즉, 최적화 방법론
# 최적화 방법론으로 SGD (Stochastic Gradient Descent) 를 사용하겠다고 설정
# learning rate => lr = 0.01
# W_t+1 := W_t - alpha*d/dw*cost(w)
optimizer = optim.SGD([W, b], lr=0.01)
# 옵티마이저 초기화
optimizer.zero_grad()
# cost계산 !!!
cost.backward()
# 옵티마이저 갱신
optimizer.step()
print(W)
print(b)

cost = torch.mean((hypothesis - y_train) ** 2)
print(cost)


✅ 여러 epoch에 대하여 제대로 학습해보자 (FULL CODE)

X_train = torch.FloatTensor([[1], [2], [3]])
y_train = torch.FloatTensor([[1], [2], [3]])

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

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

nb_epochs = 1000

for epoch in range(nb_epochs+1):
	# H(x) 계산
    hypothesis = X_train * W + b
    
    # cost 계산
    cost = (hypothesis - y_train) **2
    
    #optimizer 초기화
    optimizer.zero_grad()
    #cost계산
    cost.backward()
    #optimizer 갱신
    optimizer.step()
    
    if epoch%100 == 0:
    	print('Epoch: {:4d}/{}, W: {:.3f}, b: {:.3f}, Cost: {:.6f}.format(
        epoch, nb_epochs, W.item(), b.item(), cost.item()
        )

Q. 데이터를 테스트해보고 싶다면 ?

새로운 X를 정의하고 train된 W, b를 이용하여 값을 구하면 됨

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

0개의 댓글