finished chapter 5

This commit is contained in:
Joseph Hopfmüller
2022-10-17 00:21:56 +02:00
parent e3b6c8b90c
commit 34b6999e39
5 changed files with 113 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
import torch
# linear regression, no bias
# f = w*x
# f = 2*x
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}')