(1)线性回归是根据输入x的值,去预测输出y的值
(2)用Pytorch实现线性回归的步骤
1> Prepare dataset 准备数据集
2> Design model using Class (inherit from nn.Module) 设计模型
3> Construct loss and optimizer 构建损失函数和优化器
4> Training cycle(forward, backward, update) 训练
(3)准备数据集:假设输入x和输出y都是3x1的张量(Tensor),维度关系如下:
(4)模型设计:继承nn.Module,用线性模型实现
(5) loss损失函数使用MSELoss,使用SGD随机梯度下降更新权重
(6)代码实现
import torch
#1、用mini_batch构造数据集,x,y的值必须是矩阵
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[2.0], [4.0], [6.0]])
#2、模型设计
#构造计算图:从x输入,经过权重计算,最终经过损失函数,计算loss,计算出loss后调用反向传播,loss是个标量
#线性单元:需知道x的维度和y^的维度
#Module会自动实现backward
class LinearModel(torch.nn.Module):
#构造函数,初始化的时候需要调用
def __init__(self):
super(LinearModel, self).__init__()
#Linear包含权重和偏置,利用Linear构造对象
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
y_pred = self.linear(x)
return y_pred
model = LinearModel()
#构造损失函数和随机梯度下降优化器
#size_average是否求均值,reduce是否用求和降维
criterion = torch.nn.MSELoss(size_average=False)
#parameters()会检查model中的所有成员
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)
print(epoch, loss)
optimizer.zero_grad()#梯度清零
loss.backward()
optimizer.step()#权重更新
print('w =', model.linear.weight.item())
print('b =', model.linear.bias.item())
#Test Model
x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ', y_test.data)
最终的输出结果和预测结果有偏差:
(7)构造模型时需用到nn.Linear,这个类包含weight和bias两个Tensor
参数解析如下:
(8)在线性回归中可选用的优化器