线性回归实现
- Ai
- 7天前
- 97热度
- 0评论
线性回归
线性回归模型根据给定的数据集和对应的标签,通过一个函数模型来拟合数据集以及对应标签的映射关系。而这个模型可以设置为y=wx+b的一个函数,其中x和w是一个向量。目标就是找出权重w和偏执b的值,使得模型更逼近数据集合的规律,也就是能够预测的更准确。
线性回归示例实现
pytorch本身有线性回归的函数,只是这里通过实现pytoch来加深理解
读取数据集
def data_iter(batch_size, features, labels):
num_examples = len(features) #获取数据的长度,假1000行,输出1000
indices = list(range(num_examples)) #生成一个下标,结果[0,...,999]
random.shuffle(indices)#打散indices,使数据随机,结果[77,99,0,13,....]
for i in range(0, num_examples, batch_size): #表示从0到num_examples,步长为 batch_size
batch_indices = torch.tensor(
indices[i: min(i + batch_size, num_examples)])
print(batch_indices)
#i 到 i + batch_size 的索引转换为一 PyTorch张量
yield features[batch_indices], labels[batch_indices]
#每次循环时,yield 会返回一个元组 (features_batch, labels_batch),
#其中 features_batch 是一个包含该批次特征数据的 Tensor,labels_batch
#是该批次对应的标签数据。
定义一个函数data_iter,将数据集(x)、以及数据集对应的特征(y)作为函数输入,分割成大小为batch_size的小批量数据集(x)和特征集(y)。之所以要进行分割每次抽取小批量样本,是利用了GPU并行运算的优势。每个样本都可以并行地进行模型计算,同时在后续计算梯度时,每个样本损失函数的梯度可以被并行计算。
batch_size = 10
for X, y in data_iter(batch_size, features, labels):
print(X, '\n', y)
break
运行结果
tensor([940, 41, 385, 262, 655, 402, 317, 256, 984, 644]) --print(batch_indices)
tensor([[-0.9666, 0.8299],
[-1.8890, 0.1645],
[ 0.0274, -0.6944],
[ 2.0289, 0.7227],
[ 1.0077, 0.6674],
[ 1.8692, 0.5002],
[-0.9469, 1.7404],
[ 0.8589, -0.5467],
[ 1.1260, 0.1262],
[-0.6988, -0.0683]])
tensor([[-0.5347],
[-0.1296],
[ 6.6105],
[ 5.7961],
[ 3.9675],
[ 6.2448],
[-3.5983],
[ 7.7625],
[ 6.0183],
[ 3.0294]])
那么训练的数据集和特征怎么来了,一般是通过需要训练的目标处理得来,为了方便本章用一个函数来模拟生成数据集。
def synthetic_data(w, b, num_examples):
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))
上面这个函数,实际上就是给先指了w和b生成y=wx+b模型中的x和y, 而我们就是要训练找出w和b。
- 生成输入数据 X:torch.normal(mean, std, size) 用于从正态分布中生成数据。这里,mean=0 表示均值为0,std=1 表示标准差为1。(num_examples, len(w)) 是生成张量的形状,这里 num_examples 是生成的样本数,len(w) 是每个样本的特征数(即权重向量 w 的长度)。所以 X 是一个形状为 (num_examples, len(w)) 的矩阵,其中包含了从标准正态分布中采样的特征数据。
-
生成标签 y: torch.matmul(X, w) 计算输入特征 X 和权重 w 的矩阵乘法。结果是一个形状为 (num_examples,) 的张量,表示每个样本的预测值(不包括偏置)。+ b 将偏置 b 加到每个样本的预测值中,这样就得到最终的标签 y。这就是线性回归模型中的公式 y = Xw + b。
-
添加噪声: torch.normal(0, 0.01, y.shape) 生成一个与 y 形状相同的噪声项,噪声来自均值为 0,标准差为 0.01 的正态分布。这一步是为了给数据添加一些随机噪声,使得生成的数据更符合实际情况。现实中,数据通常会有一些误差或噪声,因此我们在标签 y 上添加小的随机波动。
-
返回数据: X 是生成的输入特征数据。y.reshape((-1, 1)) 将标签 y 转换为一个形状为 (num_examples, 1) 的列向量,以确保标签的形状是列向量。
生成合成的线性数据集,数据集的特征 X 是从标准正态分布中采样的,而标签 y 是通过线性方程 y = Xw + b 生成的,并且在 y 上添加了一些小的噪声。
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 10)
print('features:', features, '\nfeatures len', len(features), '\nlabel:', labels)
运行结果
features: tensor([[ 4.3255e-01, -1.4288e+00],
[ 2.2412e-01, -1.8749e-01],
[-5.6843e-01, 1.0930e+00],
[ 1.3660e+00, -1.8141e-03],
[ 3.9331e-01, -2.4553e-02],
[-6.3184e-01, -8.4748e-01],
[-1.7891e-02, -1.4018e+00],
[-4.8070e-01, 8.5689e-01],
[ 2.0670e+00, 3.8301e-02],
[ 1.7682e+00, 1.9595e-01]])
features len 10
label: tensor([[ 9.9307],
[ 5.2856],
[-0.6669],
[ 6.9439],
[ 5.0759],
[ 5.8344],
[ 8.9642],
[ 0.3175],
[ 8.2140],
[ 7.0458]])
定义模型
我们的模型函数是y=wX+b,也就是计算输入特征X和权重W,这里的Xw是一个向量,而b是一个标量,但是用一个向量加上一个标量是,标量会被加到每个分量上,这是广播机制。
def linreg(X, w, b):
return torch.matmul(X, w) + b
在开始计算随机梯度下降优化模型参数之前,需要先预设一些参数。下面是使用正态分布随机初始化w和b。
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
w, b
定义损失函数
损失函数就是根据我们采样处理的数据X输入到我们的模型中计算处理的值y’跟真实值y的差距,这里使用平方损失函数,即loss=(y’-y)^2,详细的公式为:L(w, b) = \frac{1}{n} \sum_{i=1}^{n} \ell^{(i)}(w, b) = \frac{1}{n} \sum_{i=1}^{n} \left( \frac{1}{2} \left( w^\top x^{(i)} + b - y^{(i)} \right)^2 \right)
def squared_loss(y_hat, y):
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
优化参数
详细的公式为:(w, b) \leftarrow (w, b) - \frac{\eta}{|B|} \sum_{i \in B} \nabla_{(w, b)} \ell^{(i)}(w, b)
损失函数是对对应参数求的偏导,即如果是w就是对w的偏导,如果是b就是b的偏导,x是当前采样的具体值(不是变量),公式中的B是抽样的小批量,是固定数量的训练样本。具体算法的步骤如下,对于W更新参数的公式为:
w \leftarrow w - \frac{\eta}{|B|} \sum_{i \in B} \frac{\partial \ell^{(i)}}{\partial w}(w, b) = w - \frac{\eta}{|B|} \sum_{i \in B} x^{(i)} \left( w^\top x^{(i)} + b - y^{(i)} \right)
对于b更新参数的公式为:
b \leftarrow b - \frac{\eta}{|B|} \sum_{i \in B} \frac{\partial \ell^{(i)}}{\partial b}(w, b) = b - \frac{\eta}{|B|} \sum_{i \in B} \left( w^\top x^{(i)} + b - y^{(i)} \right)
从上面的公式可以看出,梯度是批量误差的和,没处理一个批量数据,更新一次参数,而不是每处理一个数据更新一次参数。
def sgd(params, lr, batch_size):
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size #梯度值为param.grad
param.grad.zero_()
param.grad是哪里来的? 系统自动计算而来,下一章节会介绍。
训练
在训练之前,需要先初始化参数,
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
w, b
接下来开始训练
lr = 0.03
num_epochs = 5000
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) # 使用参数的梯度更新参数
print('true_w',true_w, 'w', w, '\ntrue_b', true_b, 'b',b)
with torch.no_grad():
train_l = loss(net(features, w, b), labels)
print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')
print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差: {true_b - b}')
为什么l.sum().backward能够自动计算存储梯度值?
在初始化w和b的参数时,设定了requires_grad=True。在计算损失时,net(X, w, b)会生成预测值y_hat,并通过loss函数与真实值y构建计算图。调用l.sum().backward()时,PyTorch的autograd系统会从标量损失l.sum()开反向传播,自动计算w和b的梯度,并存储在w.grad和b.grad中。
tensor([4, 3, 9, 6, 8, 2, 5, 7, 1, 0]) ---batch_size = 10
true_w tensor([ 2.0000, -3.4000]) w tensor([[ 2.0056],[-3.4014]], requires_grad=True)
true_b 4.2 b tensor([4.1983], requires_grad=True)
epoch 1, loss 0.000056
tensor([5, 6, 2, 4, 0, 7, 8, 1, 9, 3])
true_w tensor([ 2.0000, -3.4000]) w tensor([[ 2.0056],[-3.4014]], requires_grad=True)
true_b 4.2 b tensor([4.1983], requires_grad=True)
epoch 2, loss 0.000056
tensor([8, 5, 6, 9, 7, 4, 2, 1, 0, 3])
true_w tensor([ 2.0000, -3.4000]) w tensor([[ 2.0056],[-3.4014]], requires_grad=True)
true_b 4.2 b tensor([4.1983], requires_grad=True)
epoch 3, loss 0.000056
tensor([9, 3, 5, 2, 8, 0, 7, 4, 6, 1])
true_w tensor([ 2.0000, -3.4000]) w tensor([[ 2.0056],[-3.4014]], requires_grad=True)
true_b 4.2 b tensor([4.1983], requires_grad=True)
epoch 4, loss 0.000056
tensor([8, 1, 5, 3, 0, 6, 2, 4, 9, 7])
true_w tensor([ 2.0000, -3.4000]) w tensor([[ 2.0056],[-3.4014]], requires_grad=True)
true_b 4.2 b tensor([4.1983], requires_grad=True)
epoch 5, loss 0.000056
tensor([3, 7, 4, 0, 6, 9, 2, 1, 5, 8])
true_w tensor([ 2.0000, -3.4000]) w tensor([[ 2.0056],[-3.4014]], requires_grad=True)
true_b 4.2 b tensor([4.1983], requires_grad=True)
epoch 6, loss 0.000056
tensor([7, 4, 6, 1, 0, 5, 3, 8, 9, 2])
true_w tensor([ 2.0000, -3.4000]) w tensor([[ 2.0056],[-3.4014]], requires_grad=True)
true_b 4.2 b tensor([4.1983], requires_grad=True)
误差结果:
w的估计误差: tensor([-0.0056, 0.0014], grad_fn=<SubBackward0>)
b的估计误差: tensor([0.0017], grad_fn=<RsubBackward1>)
参考: <动手学深度学习 V2>