赞
踩
lecture05 构建线性模型
课程网址
Pytorch深度学习实践
部分课件内容
import torch x_data =torch.tensor([[1.0],[2.0],[3.0]]) y_data =torch.tensor([[2.0],[4.0],[6.0]]) class LinearModel(torch.nn.Module): def __init__(self): super(LinearModel, self).__init__() self.linear = torch.nn.Linear(1,1) # nn类构造Linear对象 包括权重和偏执 def forward(self, x): y_pred = self.linear(x) #可调用的对象 return y_pred model = LinearModel() criterion = torch.nn.MSELoss(reduction='sum') optimizer = torch.optim.SGD(model.parameters(), lr=0.01) for epoch in range(100): y_pred = model(x_data) loss = criterion(y_pred, y_data) optimizer.zero_grad() #所有梯度的权重归零 loss.backward() optimizer.step() #自动更新 print(epoch,loss.data) print('w=',model.linear.weight.data) print('b=',model.linear.bias.data) x_test = torch.tensor([[4.0]]) y_test = model(x_test) print('y_pred=',y_test.data)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。