-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyTorch_8_SGD.py
More file actions
75 lines (60 loc) · 1.69 KB
/
Copy pathPyTorch_8_SGD.py
File metadata and controls
75 lines (60 loc) · 1.69 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import torch
import matplotlib.pyplot as plt
#create some sample data
X = torch.arange(-3,3,0.1).view(-1,1)
f = 1 * X - 1
Y = f + 0.1 * torch.randn(X.size())
"""
#plot the data and the line
plt.plot(X.numpy(),f.numpy(),label = 'f')
plt.plot(X.numpy(),Y.numpy(),'ro',label = 'Y')
plt.xlabel('X')
plt.ylabel('f/Y')
plt.legend()
plt.show()
"""
def forward(x):
return w * x + b
def criterion(y_pred,y):
return torch.mean((y_pred - y) ** 2)
w = torch.tensor(-15.0,requires_grad=True)
b = torch.tensor(-10.0,requires_grad=True)
lr = 0.1
LOSS_BGD = []
EPOCH = []
def train_model_BGD(iter):
for epoch in range(iter):
y_pred = forward(X)
loss = criterion(y_pred,Y)
LOSS_BGD.append(loss.item())
EPOCH.append(epoch)
loss.backward()
w.data = w.data - lr * w.grad.data
b.data = b.data - lr * b.grad.data
w.grad.data.zero_()
b.grad.data.zero_()
train_model_BGD(10)
w = torch.tensor(-15.0,requires_grad=True)
b = torch.tensor(-10.0,requires_grad=True)
lr = 0.1
LOSS_SGD = []
EPOCH = []
def train_model_SGD(iter):
for epoch in range(iter):
LOSS_SGD.append(criterion(forward(X),Y).item())
EPOCH.append(epoch)
for x,y in zip(X,Y):
y_pred = forward(x)
loss = criterion(y_pred,y)
loss.backward()
w.data = w.data - lr * w.grad.data
b.data = b.data - lr * b.grad.data
w.grad.data.zero_()
b.grad.data.zero_()
train_model_SGD(10)
plt.plot(LOSS_BGD,EPOCH,label='BGD')
plt.plot(LOSS_SGD,EPOCH,label='SGD')
plt.xlabel('Epoch')
plt.ylabel('LOSS')
plt.legend()
plt.show()