import torch
x_data = [1,2,3]
y_data = [2,4,6]
w = torch.Tensor([1.0])
w.requires_grad = True
def forward(x):
return w*x
def loss(x, y):
y_pred = forward(x)
return (y_pred-y)**2
for epoch in range(30):
sum=0
for x,y in zip(x_data,y_data):
l = loss(x,y)
l.backward()
w.data = w.data - 0.01*w.grad.data
sum += l.item()
w.grad.data.zero_()
print(f'epoch:{epoch},w={w.data.item():.2f},loss={l.item():.2f}')
epoch:0,w=1.26,loss=7.32
epoch:1,w=1.45,loss=4.00
epoch:2,w=1.60,loss=2.19
epoch:3,w=1.70,loss=1.19
epoch:4,w=1.78,loss=0.65
epoch:5,w=1.84,loss=0.36
epoch:6,w=1.88,loss=0.20
epoch:7,w=1.91,loss=0.11
epoch:8,w=1.93,loss=0.06
epoch:9,w=1.95,loss=0.03
epoch:10,w=1.96,loss=0.02
epoch:11,w=1.97,loss=0.01
epoch:12,w=1.98,loss=0.01
epoch:13,w=1.99,loss=0.00
epoch:14,w=1.99,loss=0.00
epoch:15,w=1.99,loss=0.00
epoch:16,w=1.99,loss=0.00
epoch:17,w=2.00,loss=0.00
epoch:18,w=2.00,loss=0.00
epoch:19,w=2.00,loss=0.00
epoch:20,w=2.00,loss=0.00
epoch:21,w=2.00,loss=0.00
epoch:22,w=2.00,loss=0.00
epoch:23,w=2.00,loss=0.00
epoch:24,w=2.00,loss=0.00
epoch:25,w=2.00,loss=0.00
epoch:26,w=2.00,loss=0.00
epoch:27,w=2.00,loss=0.00
epoch:28,w=2.00,loss=0.00
epoch:29,w=2.00,loss=0.00