-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLR_automated_PyTorch.py
More file actions
59 lines (40 loc) · 1.47 KB
/
Copy pathLR_automated_PyTorch.py
File metadata and controls
59 lines (40 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Converting everything to tensors and using AutoGrad
# from PyTorch to implement the gradient function, using torch.nn to implement
# loss and torch.optim() for optimizer
# Implementing Linear Regression using manual functions
# Function we will use to build and test our model
# F(x) = 2 * X
# F'(x) = w * x. We need to find the value of w(weight)
import torch
import torch.nn as nn
X = torch.tensor([[1],[2],[3],[4]], dtype=torch.float32) # Training examples
Y = 2 * X # Output Function that is to be simulated
print(X)
print(Y)
X_test = torch.tensor([5], dtype=torch.float32)
n_samples, n_features = X.shape
input_size = n_features
output_size = n_features
model = nn.Linear(input_size, output_size)
# Model Prediction
print(f'Prediction before training for x = 5. It gives {model(X_test).item():.3f}')
# Training
learning_rate = 0.01
epochs = 100
loss = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)
for epoch in range(epochs):
# prediction = forward pass
y_pred = model(X)
# loss
l = loss(Y, y_pred)
# gradient
l.backward() # dl/dw
# update weights
optimizer.step()
# zero gradient
optimizer.zero_grad()
if epoch%10 == 0:
w,b = model.parameters()
print(f'Epoch {epoch+1}: \n w = {w[0][0].item():.3f}, loss = {l:.8f}')
print(f'Prediction after training for x =5 .It gives {model(X_test).item():.3f}')