动手学习深度学习(3)简单的线性回归

茴香豆 Lv5

本节将学习一些线性回归基础知识和线性回归的简洁实现。

1. 线性回归

线性回归是最简单的模型,也是一个非常重要的基础模型。可以视作一个单层的神经网络。唯一有最优解的模型。

基础优化方法:梯度下降

梯度下降的学习率既不能太小,也不能太大。

一般不会直接采用梯度下降,而是采用小批量随机梯度下降 。当数据量过大时,我们可以随机采样b个样本(b是批量大小),用他们损失的平均值来近似损失。同样批量大小b不能太小也不能太大。小批量随机梯度下降是深度学习默认的求解算法。

2. 线性回归从零开始实现

我们将从零开始实现整个方法,包括数据流水线、模型、损失函数和小批量随机梯度下降优化器。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
%matplotlib inline
import random
import torch
from d2l import torch as d2l

def synthetic_data(w, b, num_examples):
"""生成 y = Xw + b + 噪声"""
X = torch.normal(0, 1, (num_examples, len(w)))
#生成X,均值为0,标准差为1的随机数。大小为num_examples x len(w)的矩阵。
y = torch.matmul(X, w) + b
y += torch.normal(0, 0.01, y.shape)
#给y加上噪音,噪音均值为0,标准差为0.01,与y形状相同。
return X, y.reshape((-1, 1))#将y整理为一列的向量(虽然此处并不必要)

true_w = torch.tensor([2, -3.4])
true_b = 4.2
# 生成训练样本features, labels
features, labels = synthetic_data(true_w, ture_b, 1000)
# 读取数据集
def deta_iter(batch_size, features, labels):
'''该函数接收批量大小等输入,生成大小为batch_size的小批量'''
num_examples = len(features)
indices = list(range(num_examples))
# 这些样本是随机读取的,没有特定的顺序
random.shuffle(indices)
for i in range(0, num_examples, batch_size):
batch_indices = torch.tensor(indices[i:min(i + batch_size, num_examples)])
yield features[batch_indices], labels[batch_indices]

batch_size = 10
w = torch.normal(0, 0.01, size=(2, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)

def linreg(X, w, b):
'''线性回归模型'''
return torch.matmul(X, w) + b

def squared_loss(y_hat, y):
'''均方损失'''
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2

def sgd(params, lr, batch_size):
'''小批量随机梯度下降'''
with torch.no_grad():
# torch.no_grad()用于停止autograd模块的工作
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_()

训练过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
lr = 0.03
num_epochs = 3 #整个数据扫3遍
net = linreg
loss = squared_loss

for epoch in range(num_epochs):
for X, y in data_iter(batch_size, features, labels):
l = loss(net(X, w, b), y)
# 因为l形状是(batch_size, 1), 而不是一个标量。l中的所有元素被加到一起,
# 并以此计算[w, b]的梯度
l.sum().backward()
sgd([w, b], lr, batch_size) # 使用参数的梯度更新参数
with torch.no_grad():
train_l = loss(net(features, w, b), labels)
print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')

比较真实参数和通过训练学到的参数来评估训练的成功程度

1
2
3
4
5
print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差: {true_b - b}')
# output:
w的估计误差: tensor([0.0004, -0.0003])
b的估计误差: tensor([0.0008])

3. 线性回归的简洁实现

我们将介绍如何通过使用深度学习框架来简洁地实现上小节中的线性回归模型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 生成数据集
import numpy as np
import troch
from troch.utils import data
from d2l import torch as d2l

true_w = troch.tensor([2, -3.4])
true_b = 4.2
# 人工数据生成函数生成features和labels
features, labels = d2l.synthetic_data(true_w, true_b, 1000)

# 调用框架现有的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)
# iter()生成迭代器函数,next()返回迭代器的下一个项目
next(iter(data_iter))

# 使用框架的预定义好的层
from torch import nn
net = nn.Sequential(nn.Linear(2, 1))#输入维度2,输出维度1
# 初始化模型参数
net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)
# 均方误差
loss = nn.MSELoss()
# 实例化SGD实例,net.parameters():拿出所有参数,lr:指定学习率0.03
trainer = torch.optim.SGD(net.parameters(), lr=0.03)

#训练
num_epochs = 3
for epochs 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'epochs {epoch + 1}, loss {1:}')
  • Title: 动手学习深度学习(3)简单的线性回归
  • Author: 茴香豆
  • Created at : 2022-09-26 20:21:03
  • Updated at : 2022-09-27 18:40:10
  • Link: https://hxiangdou.github.io/2022/09/26/DL_3/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments