详见视频:https://www.bilibili.com/video/BV1Y7411d7Ys?p=1
# 总体思路:前馈-反馈-更新
import torch
x_data = torch.Tensor([[1.0], [2.0], [3.0]]) #准备x
y_data = torch.Tensor([[2.0], [4.0], [6.0]]) #准备y 从这里可以看出w是2,因为y = x * w
class LinearModel(torch.nn.Module):
def __init__(self):
super(LinearModel, self).__init__() #写上就完了
self.linear = torch.nn.Linear(1,1) #给定w还有b的维数
def forward(self,x): #前馈
y_pred = self.linear(x)
return y_pred
model = LinearModel() #实例化model
criterion = torch.nn.MSELoss(size_average=False) #构建损失函数
optimizer = torch.optim.SGD(model.parameters(),lr = 0.01) #优化器
for epoch in range(100): #开始训练
y_pred = model(x_data) #计算y^
loss = criterion(y_pred,y_data) #计算损失
print(epoch,loss.item())
optimizer.zero_grad() #优化
loss.backward() #反向传播
optimizer.step() #更新
print('w = ',model.linear.weight.item())
print('b = ',model.linear.bias.item())
x_test = torch.Tensor([[4.0]]) #测试
y_test = model(x_test)
print('y_pred = ',y_test.data)