# 线性回归的从零开始实现
import random
import torch
from d2l import torch as d2l
import matplotlib.pyplot as plt
# 根据带有噪声的线性模型构造一个人造数据集。使用线性模型参数w=[2,-3.4]T、b=4.2和噪声项∈生成数据集及其标签:y=Xw+b+∈
def synthetic_data(w, b, num_examples):
X = torch.normal(0, 1, (num_examples, len(w))) # torch.normal(mean, std, size),生成均值为0,方差为1的随机数,大小为num_examples行×len(w)列的矩阵
y = torch.matmul(X, w) + b # torch.matmul()是tensor的乘法,输入可以是高维的
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('feature:', features[0], '\nlabel:', labels[0])
#
# d2l.set_figsize()
# d2l.plt.scatter(features[:, 1].detach().numpy(), labels.detach().numpy(), 1)
# plt.show()
# 读取人造数据集:该函数能打乱数据集中的样本并以小批量方式获取数据
# 小批量随机梯度下降法:定义一个data_iter函数,该函数接受批量大小、特征矩阵和标签向量作为输入,生成大小为batch_size的小批量
def data_iter(batch_size, features, labels):
num_examples = len(features) # 定义样本数量
indices = list(range(num_examples)) # 生成0~n-1的python序列,即[0,1,2,...,n-1]
# 这些样本是随机读取的,没有特定的顺序
random.shuffle(indices) # random.shuffle()用于将一个列表中的元素打乱顺序,值得注意的是使用这个方法不会生成新的列表,只是将原列表的次序打乱
for i in range(0, num_examples, batch_size): # 遍历0~n-1,间隔为batch_size
batch_indices = torch.tensor(indices[i:min(i + batch_size, num_examples)])
yield features[batch_indices], labels[batch_indices]
batch_size = 10
# d2l.set_figsize()
# d2l.plt.scatter(X[:, 1].detach().numpy(), y.detach().numpy(), 1)
# plt.show()
# 定义初始化模型参数
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): # 给定参数列表w和b,给定学习率,给定批量大小
"""小批量随机梯度下降"""
with torch.no_grad(): # 使用with torch.no_grad():表明当前计算不需要反向传播,使用之后,强制后边的内容不进行计算图的构建(即不需要计算梯度)
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_()
# 训练过程
lr = 0.03 # 学习率=0.03
num_epochs = 3 # 数据扫三遍
net = linreg # 模型为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.sum().backward() # 因为l的形状是(batch_size,1),而不是一个标量,l中的所有元素被加到一起,并以此计算关于[w,b]的梯度
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}')
print(f'w的估计误差:{true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差:{true_b - b}')
跟着李沐的深度学习视频写的,刚开始学,还有很多看不懂的代码,尽我所能标注了一些注释,如果有错误的地方欢迎指正。