import torch
x_da = [1.0,2.0,3.0]
y_da = [2.0,4.0,6.0]
w = torch.Tensor([1.0])
w.requires_grad = True
def forward(x):
return w * x
def loss(x , y):
return (forward(x) - y)**2
epoc = []
costs = []
for epo in range(100):
for xs, ys in zip(x_da ,y_da):
l = loss(xs,ys)
l.backward()
w.data = w.data - 0.01 * w.grad.data #w.grad.data == w.grad.item()
w.grad.zero_()
costs.append(l.item())
epoc.append(epo)
print(costs)
print("predict (after training)", 4, forward(4.0).item())
##################################
import torch
x_da = [1.0,2.0,3.0]
y_da = [2.0,4.0,6.0]
w = torch.Tensor([1.0])
w.requires_grad = True
def forward(x):
return w * x
def loss(x , y):
return (forward(x) - y)**2
epoc = []
costs = []
for epo in range(100):
for xs, ys in zip(x_da ,y_da):
l = loss(xs,ys)
l.backward()
w.data = w.data - 0.01 * w.grad.item() #w.grad.data == w.grad.item()
w.grad.zero_()
costs.append(l.item())
epoc.append(epo)
print(costs)
print("predict (after training)", 4, forward(4.0).item())
#
# import matplotlib.pyplot as plt
对比记录