代码取自B站刘二老师的《Pytorch深度学习实践》视频教程
import torch
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
w = torch.tensor([1.0])
w.requires_grad = True # 需要计算梯度
def forward(x):
return x * w
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) ** 2
print(("predict before training", 4, forward(4).item())) # 在pytorch中 item是得到一个元素张量里面的元素值
for epoch in range(100):
for x, y in zip(x_data, y_data):
l = loss(x, y)
l.backward()
print('\tgrad:', x, y, w.grad.item()) # tensor中的grad也是tensor
w.data = w.data - 0.01 * w.grad.data
w.grad.data.zero_()
print("progress:", epoch, l.item())
print("predict after training", 4, forward(4).item())