Preparation
小白,仅作为个人笔记。
%matplotlib inline
# jupyter notebook 画图用,%可以将matplotlib的图标直接嵌入到Notebook中。
# inline表示将图标嵌入到notebook中。
import random
# 随机初始化权重和随机梯度下降。
import torch
from d2l import torch as d2l
# 用过的算法和函数放在d2l的包里面
# 因为是基于pytorch实现的,所以从d2l里面导入torch的模具。
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)
# torch.normal()生成标准正态分布的随机数
# torch.matmul()两个矩阵相乘
2.读取数据集
def data_iter(batch_size, features, labels):
#batch_size为批量大小,features和labels为数据集。
num_examples = len(features)
indices = list(range(num_examples))
# 这些样本是随机读取的,没有特定的顺序
random.shuffle(indices)
# 把下标indices完全打乱
for i in range(0, num_examples, batch_size):
#从0开始一直到数据的结尾,每次跳batch_size的距离
batch_indices = torch.tensor(
indices[i: min(i + batch_size, num_examples)])
#取得是indices的下标,但是indices是乱序的
#所以batch_indices是乱序,对于features和labels是随机的。
yield features[batch_indices], labels[batch_indices]
#yield会终止for循环,所以每次for循环都执行一次
batch_size = 10
for X, y in data_iter(batch_size, features, labels):
print(X, '\n', y)
上面实现的迭代对教学来说很好,但它的执行效率很低,可能会在实际问题上陷入麻烦。 例如,它要求我们将所有数据加载到内存中,并执行大量的随机内存访问。 在深度学习框架中实现的内置迭代器效率要高得多, 它可以处理存储在文件中的数据和数据流提供的数据。(粘贴的)
3.初始化模型参数
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
在初始化参数之后,我们的任务是更新这些参数,直到这些参数足够拟合我们的数据。 每次更新都需要计算损失函数关于模型参数的梯度。 有了这个梯度,我们就可以向减小损失的方向更新每个参数。
4.定义模型
def linreg(X, w, b):
"""线性回归模型"""
return torch.matmul(X, w) + b
5.定义损失函数
def squard_loss(y_hat, y):
"""均方损失函数"""
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
在这里,需要将真实值y的形状转换为和预测值y_hat的形状相同。
6. 定义优化算法
def sgd(params, lr, batch_size)
"""小批量随机梯度下降"""
with torch.no.grad()
for param in params:
param -= lr*param.grad / batch_size
param.grad.zeros_()
7.训练
步骤:
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}')