52 lines
1.1 KiB
Python
52 lines
1.1 KiB
Python
# prediction manual
|
|
# gradient computation autograd -> gradient computation gets replaced by backward()
|
|
# loss computation manual
|
|
# parameter update manual
|
|
|
|
# linear regression, no bias
|
|
# f = 2*x
|
|
|
|
import torch
|
|
|
|
|
|
X = torch.tensor([1, 2, 3, 4], dtype=torch.float32)
|
|
Y = torch.tensor([2, 4, 6, 8], dtype=torch.float32)
|
|
|
|
w = torch.tensor(0.0, dtype=torch.float32, requires_grad=True) #requires grad for gradient
|
|
|
|
# model prediction
|
|
def forward(x):
|
|
return w*x
|
|
|
|
# loss = MSE
|
|
def loss(y, y_pred):
|
|
return ((y_pred - y)**2).mean()
|
|
|
|
|
|
print(f'Prediction before training: f(5) = {forward(5):.3f}')
|
|
|
|
#Training
|
|
learning_rate = .01
|
|
n_iters = 100
|
|
|
|
for epoch in range(n_iters):
|
|
# prediction = forward pass
|
|
y_pred = forward(X)
|
|
|
|
# loss
|
|
l = loss(Y, y_pred)
|
|
|
|
# gradients = backward pass
|
|
l.backward()
|
|
|
|
#update weights
|
|
with torch.no_grad():
|
|
w -= learning_rate*w.grad
|
|
|
|
w.grad.zero_()
|
|
|
|
if epoch % 10 == 0: #every nth epoch
|
|
print(f'epoch {epoch+1}: w = {w:.3f}, loss = {l:.8f}')
|
|
|
|
print(f'Prediction after training: f(5) = {forward(5):.3f}')
|