
import numpy
import torch.optim as optim
# For reproducibility - 매번 실행할때마다 코드의 결과 값을 동일하게 하기 위한 과정
torch.manual_seed(1)
# (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]])
print(x_train)
print(x_train.shape)

print(y_train)
print(y_train.shape)

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

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

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


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

# 최적화 방법론으로 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)

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

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