线性回归简洁实现

时间:2024-10-22 13:43:16

1.通过使用深度学习框架来简洁实现线性回归模型生成数据集

import numpy as np
import torch
from torch.utils import data
from d2l import torch as d2l

true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = d2l.synthetic_data(true_w, true_b, 1000)

2.调用框架现有API来读取数据

def load_array(data_arrays, batch_size, is_train=True):
    """构造Pytorch数据迭代器"""
    dataset = data.TensorDataset(*data_arrays)
    return data.DataLoader(dataset, batch_size, shuffle=is_train)

batch_size=10
data_iter=load_array((features, labels),batch_size)

next(iter(data_iter))

3.使用框架预定义好的层

from torch import nn

net = nn.Sequential(nn.Linear(2, 1))

4.初始化模型参数

net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)

5.计算均方误差使用的是MSELoss类(平方范式)

loss = nn.MSELoss()

6.实例化SGD实例

trainer = torch.optim.SGD(net.parameters(), lr=0.03)

7.训练过程代码

num_epochs = 3
for epoch in range(num_epochs):
    for X, y in data_iter:
        l = loss(net(X), y)
        trainer.zero_grad()
        l.backward()
        trainer.step()
    l = loss(net(features), labels)
    print(f'epoch{epoch + 1},loss {1:f}')