-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyTorch_03.py
More file actions
48 lines (36 loc) · 1.21 KB
/
PyTorch_03.py
File metadata and controls
48 lines (36 loc) · 1.21 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
#Linear Regression
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
#input variable / features / independent variable
x_data = Variable(torch.Tensor([[1.0],[2.0],[3.0]]))
#target variable / dependent variable
y_data = Variable(torch.Tensor([[2.0],[4.0],[6.0]]))
#Step - 1 Model class
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear = nn.Linear(1,1)
def forward(self,x):
y_pred = self.linear(x)
return y_pred
model = Model()
#Step 2 - Construct Loss criterion and Optimizer
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(),lr = 0.01)
#Step 3 Training - Forward - Backward - Step
for epoch in range(500):
#Forward pass : compute predicted y by passing x to the model
y_pred = model(x_data)
#Compute loss
loss = criterion(y_pred,y_data)
print(epoch,loss.item())
#Zero gradients
optimizer.zero_grad()
#perform backward pass
loss.backward()
#update the weights
optimizer.step()
hour_var = Variable(torch.Tensor([[4.0]]))
print("Prediction after training",4,model.forward(hour_var).data[0][0])