
가설함수 (모델)비용함수(비용)** [주의] 식을 간소화 하기 위해 가설함수에 편향변수 b를 추가히자 않았음.
# 시각화용 라이브러리
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)

# -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()

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된 것을 확인할 수 있었어.
# 데이터
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이 아니라 *로 한 것

# 데이터
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()
