算法思路:
这段代码实现了一个简单的线性回归模型,并使用随机梯度下降算法对模型进行训练。
算法流程:
import random
import torch
导入所需的库:random
用于随机数生成,torch
用于深度学习框架。
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)
synthetic_data
函数用于生成合成数据。它接受权重w
、偏置b
和样本数量num_examples
作为输入,并生成服从正态分布的特征X
和对应的标签y
。标签y
由特征X
和权重w
以及偏置b
计算得到,然后添加了服从正态分布的噪声。
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]
data_iter
函数用于生成小批量数据。它接受批量大小batch_size
、特征features
和标签labels
作为输入,并返回一个生成器,每次生成一个批量的特征和标签。函数内部通过随机打乱样本的索引,然后按照批量大小分割数据。取min(i+batch_size,num_examples) 是为了防止列表越界。
def linreg(X, w, b):
return torch.matmul(X, w) + b
linreg
函数定义了线性回归模型,它接受特征X
、权重w
和偏置b
作为输入,并返回模型的预测结果。
def squared_loss(y_hat, y):
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
squared_loss
函数定义了均方损失函数,它接受预测值y_hat
和真实值y
作为输入,并返回损失值。
def sgd(params,lr,batch_size):
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_()
sgd
函数实现了随机梯度下降算法。它接受参数列表params
、学习率lr
和批量大小batch_size
作为输入,并更新参数的值。在每次更新参数之前,使用param.grad.zero_()
将参数的梯度清零。
lr = 0.01
num_epochs = 10
net = linreg
loss = squared_loss
batch_size = 10
w = torch.normal(0, 0.01, size=(2, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
true_w = torch.tensor([2,-3.4])
true_b = 4.2
features,labels = synthetic_data(true_w,true_b,1000)
设置超参数和模型参数。学习率lr
为0.01,迭代次数num_epochs
为10,模型为线性回归模型net
,损失函数为均方损失函数loss
,批量大小batch_size
为10。初始化模型参数w
和b
,并生成合成数据作为训练集,其中真实权重和偏置为true_w
和true_b
。
for epoch in range(num_epochs):
for X,y in data_iter(batch_size,features,labels):
l = loss(net(X,w,b),y)
l.sum().backward(retain_graph = True)
sgd([w,b],lr,batch_size)
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}')
使用随机梯度下降算法进行模型训练。在每个迭代周期中,通过data_iter
函数生成小批量数据,计算模型的预测值并计算损失。然后调用backward
函数计算梯度,并使用sgd
函数更新模型参数。在每个迭代周期结束后,计算整个训练集上的损失并打印出来。最后,打印出估计的权重w
和偏置b
与真实值的误差。
结果:
epoch1,loss2.385253
epoch2,loss0.372472
epoch3,loss0.058790
epoch4,loss0.009393
epoch5,loss0.001546
epoch6,loss0.000291
epoch7,loss0.000089
epoch8,loss0.000056
epoch9,loss0.000051
epoch10,loss0.000050
w的估计误差:tensor([0.0002, 0.0001], grad_fn=<SubBackward0>)
b的估计误差:tensor([-7.6771e-05], grad_fn=<RsubBackward1>)