线性回归的基本元素包括:线性模型、损失函数、解析解、随机梯度下降、模型预测。从零开始实现整个方法,包括数据流水线、模型、损失函数和小批量随机梯度下降优化器。
生成数据集
生成一个包含1000个样本的数据集,每个样本包含从标准正态分布中抽样的两个特征。
使用线性模型参数 w = [ 2 , − 3.4 ] T w=[2,-3.4]^T w=[2,−3.4]T$b=4.2$和噪声项来生成数据集和标签
def synthetic_data(w, b, num_examples):
X = torch.normal(0, 1, (num_examples, len(w))) # (生成均值为0,方差为1的随机数)
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=data_generator.synthetic_data(true_w,true_b,1000)
features中的每一行包含一个二维数据样本,labels中的每一行包含一个标签值。
print('features: ',features[0],'\nlabel: ',labels[0])
features: tensor([-1.8352, -1.4149])
label: tensor([5.3331])
读取数据集
训练模型时要对数据集进行遍历,每次抽取小批量样本,并更新模型。
定义一个迭代器函数生成小批量函数(接收批量大小、特征矩阵、标签,生成大小为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]
初始化模型参数
在使用小批量随机梯度下降优化模型参数前,需要先有一些参数,即初始化参数。
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():
for param in params:
param-=lr*param.grad/batch_size
param.grad.zero_()
训练
训练部分:
- 初始化参数
- 重复以下训练直到完成:(计算梯度、更新参数)
每轮训练,都要使用迭代器获取小批量数据
lr = 0.03
num_epochs = 3
net = model.linreg
loss = loss.squared_loss
for epoch in range(num_epochs):
for X,y in data_iter.data_iter(batch_size,features,labels):
l=loss(net(X,w,b),y)
l.sum().backward()
optimizor.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}')