In [1]:
import torch
import numpy as np
from torch.autograd import Variable # Autograd
from torch import nn # Basic Neural Network Module
import matplotlib.pyplot as plt # Needs for Ploting
from scipy.stats import norm
In [2]:
sample_size = 100
x = torch.FloatTensor(sample_size, 1).uniform_(-1, 1)
y = 2*x + torch.randn(x.size())
plt.scatter(x, y)
plt.title("y=ax+b")
plt.grid()
plt.show()
In [ ]:
# Model 정의
model = nn.Linear(1, 1, bias=True)
cost_function = nn.MSELoss() # Mean Squared Cost Function
optimizer = torch.optim.SGD(model.parameters(), lr=0.05) # 일단 그려려니 하고 넘어가자
print(model)
print(model.weight, model.bias)
In [5]:
# Training
epoch = 100
for step in range(epoch):
prediction = model(x) # model에 x를 넣어서 예측값을 만든다.
cost = cost_function(prediction, y) # cost function으로 얼마나 잘했는지 판단(예측, 원결과)
optimizer.zero_grad() # 일단은 그려려니하고 넘어가자
cost.backward()
optimizer.step()
if not(step % 20):
plt.cla()
plt.scatter(x, y)
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=1)
plt.title('cost=%.4f, w=%.4f, b=%.4f' % (cost.item(), model.weight.item(),model.bias.item()), fontdict={'size': 20} )
plt.grid()
plt.show()
plt.pause(0.1)
In [ ]:
In [ ]: