本节内容主要是讲解使用深度学习框架后的线性回归简洁实现
原理部分可以参照
线性回归理论介绍
线性回归从零开始实现
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) # 生成人工数据,函数实现在 线性回归从零开始实现文章中
net = nn.Sequential(nn.Linear(2, 1))
net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)
计算均方误差使用的是MSELoss类,也称为平方 2 范数
loss = nn.MSELoss()
trainer = torch.optim.SGD(net.parameters(), lr=0.03)
import numpy as np
import torch
from torch.utils import data
from d2l import torch as d2l
from torch import nn
# 真实权重和偏差参数
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = d2l.synthetic_data(true_w, true_b, 1000) # 生成人工数据,函数实现在 线性回归从零开始实现文章中
def load_array(features, labels, batch_size, is_train=True):
"""构造一个PyTorch数据迭代器。"""
dataset = data.TensorDataset(features, labels) # features需要被封装的数据样本,labels需要被封装的数据标签
return data.DataLoader(dataset, batch_size, shuffle=is_train)
batch_size = 10
data_iter = load_array(features, labels, batch_size)
print(next(iter(data_iter)))
net = nn.Sequential(nn.Linear(2, 1))
net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)
loss = nn.MSELoss()
trainer = torch.optim.SGD(net.parameters(), lr=0.03)
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 {l:f}')