文章目录
3.2 线性回归的从零开始实现
在这一节中,从零开始实现整个方法, 包括数据流水线、模型、损失函数和小批量随机梯度下降优化器。
%matplotlib inline
import random
import torch
from d2l import torch as d2l
3.2.1. 生成数据集
def synthetic_data(w, b, num_examples): #@save
"""生成y=Xw+b+噪声"""
X = torch.normal(0, 1, (num_examples, len(w)))
y = torch.matmul(X, w) + b
y += torch.normal(0, 0.01, y.shape)
return X, y.reshape((-1, 1))
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 1000)
注意,features中的每一行都包含一个二维数据样本, labels中的每一行都包含一维标签值(一个标量)。
print('features:', features[0],'\nlabel:', labels[0])
features: tensor([-0.1413, 0.9253])
label: tensor([0.7524])
通过生成第二个特征features[:, 1]和labels的散点图, 可以直观观察到两者之间的线性关系。
d2l.set_figsize()
d2l.plt.scatter(features[:, (1)].detach().numpy(), labels.detach().numpy(), 1);
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tocii8tM-1662219490646)(https://zh.d2l.ai/_images/output_linear-regression-scratch_58de05_42_0.svg)]
3.2.2. 读取数据集
定义一个data_iter函数, 该函数接收批量大小、特征矩阵和标签向量作为输入,生成大小为batch_size的小批量。 每个小批量包含一组特征和标签。
def data_iter(batch_size, features, labels):
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
for X, y in data_iter(batch_size, features, labels):
print(X, '\n', y)
break
tensor([[-0.0929, 0.3136],
[-0.4081, 0.5990],
[ 1.2006, -0.8625],
[ 2.8351, 1.2113],
[ 0.4811, 1.6206],
[-1.5946, 0.7590],
[-0.7296, 2.0734],
[ 1.4357, -0.4068],
[-1.1405, -0.0359],
[ 0.6749, 0.9677]])
tensor([[ 2.9562],
[ 1.3347],
[ 9.5308],
[ 5.7467],
[-0.3549],
[-1.5650],
[-4.3218],
[ 8.4510],
[ 2.0353],
[ 2.2612]])
3.2.3. 初始化模型参数
从均值为0、标准差为0.01的正态分布中采样随机数来初始化权重, 并将偏置初始化为0。
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
3.2.4. 定义模型
def linreg(X, w, b): #@save
"""线性回归模型"""
return torch.matmul(X, w) + b
3.2.5. 定义损失函数
def squared_loss(y_hat, y): #@save
"""均方损失"""
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
3.2.6. 定义优化算法
从数据集中随机抽取的一个小批量,然后根据参数计算损失的梯度。 接下来,朝着减少损失的方向更新我们的参数.
def sgd(params, lr, batch_size): #@save
"""小批量随机梯度下降"""
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_()
3.2.7. 训练
在每次迭代中,我们读取一小批量训练样本,并通过我们的模型来获得一组预测.
计算完损失后,我们开始反向传播,存储每个参数的梯度。
最后,我们调用优化算法sgd来更新模型参数
lr = 0.03
num_epochs = 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) # X和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}')
epoch 1, loss 0.026352
epoch 2, loss 0.000093
epoch 3, loss 0.000054
通过比较真实参数和通过训练学到的参数来评估训练的成功程度。
事实上,真实参数和通过训练学到的参数确实非常接近。
print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差: {true_b - b}')
w的估计误差: tensor([ 0.0002, -0.0001], grad_fn=<SubBackward0>)
b的估计误差: tensor([0.0006], grad_fn=<RsubBackward1>)
在复杂的优化问题上,随机梯度下降通常也能找到非常好的解。 其中一个原因是,在深度网络中存在许多参数组合能够实现高度精确的预测
机器学习中,通常不太关心恢复真正的参数,而更关心如何高度准确预测参数
3.2.8. 小结
-
我们学习了深度网络是如何实现和优化的。在这一过程中只使用张量和自动微分,不需要定义层或复杂的优化器。
-
这一节只触及到了表面知识。在下面的部分中,我们将基于刚刚介绍的概念描述其他模型,并学习如何更简洁地实现其他模型。