目录
08 线性回归 + 基础优化算法
1.线性回归
2.基础优化算法
3.线性回归的从零开始实现
4.线性回归的简洁实现
import random
import torch
from d2l import torch as d2l
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# 根据带有噪声的线性模型构造一个人造数据集。我们使用线性模型参数w=[2, -3.4]T、b=4.2和噪声项生成数据集及其标签
def synthetic_data(w, b, num_examples):
'''生成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)
# features中的每一行都包含一个二维数据样本,labels中的每一行都包含一维标签值(一个标量)
print('features:', features[0], '\nlabel:', labels[0])
d2l.set_figsize()
d2l.plt.scatter(features[:, 1].detach().numpy(), labels.detach().numpy(), 1)
d2l.plt.show()
# 定义一个data_iter函数,该函数接收批量大小、特征矩阵和标签向量作为输入,生成大小为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]
batch_size = 10
for X, y in data_iter(batch_size, features, labels):
print(X, '\n', y)
break
# 初始化模型参数
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 = 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),而不是一个标量。‘1’中所有元素被加到一起,并以此计算关于['w', 'b']的梯度
l.sum().backward()
sgd([w, b], lr, batch_size) # 使用参数的梯度更新参数
with torch.no_grad():
train_1 = loss(net(features, w, b), labels)
print(f'epoch{epoch + 1}, loss {float(train_1.mean()):f}')
# 比较真实参数和通过训练学到的参数来评估训练的成功程度
print(f'w的估计误差:{true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差:{true_b - b}')
features: tensor([ 0.0973, -1.7033])
label: tensor([10.1773])
tensor([[-1.0356, -0.0742],
[ 0.9682, -1.4913],
[ 0.8067, -1.2646],
[ 1.3020, -1.8027],
[-0.7537, 1.3895],
[-0.2976, 0.7681],
[ 0.4596, 0.5063],
[ 0.2284, -0.1043],
[ 0.7668, 0.4456],
[ 0.5379, -0.5702]])
tensor([[ 2.3705],
[11.2128],
[10.1043],
[12.9313],
[-2.0407],
[ 0.9963],
[ 3.3958],
[ 5.0220],
[ 4.2043],
[ 7.2166]])
epoch1, loss 0.034227
epoch2, loss 0.000124
epoch3, loss 0.000053
w的估计误差:tensor([-0.0002, -0.0004], grad_fn=)
b的估计误差:tensor([-0.0002], grad_fn=)
# 通过使用深度学习框架来简洁地实现线性回归模型生成数据集
import numpy as np
import torch
from torch.utils import data
from d2l import torch as d2l
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = d2l.synthetic_data(true_w, true_b, 1000)
# 调用框架中现有的API来读取数据
def load_array(data_arrays, batch_size, is_train=True):
'''构造一个PyTorch数据迭代器'''
dataset = data.TensorDataset(*data_arrays)
return data.DataLoader(dataset, batch_size, shuffle=is_train)
batch_size = 10
data_iter = load_array((features, labels), batch_size)
print(next(iter(data_iter)))
# 使用框架的预定义好的层
# 'nn'是神经网络的缩写
from torch import nn
net = nn.Sequential(nn.Linear(2, 1))
# 初始化模型参数
net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)
# 计算均方误差使用的是MSELoss类,也称为平方L2范数
loss = nn.MSELoss()
# 实例化SGD实例
trainer = torch.optim.SGD(net.parameters(), lr=0.03)
# 训练过程代码与我们从零开始实现时所做的非常相似
num_epochs = 3
for epoch in range(num_epochs):
for X, y in data_iter:
l = loss(net(X), y)
trainer.zero_grad()
l.backward()
trainer.step()
l = loss(net(features), labels)
print(f'epoch {epoch+1}, loss {l:f}')
[tensor([[-1.2176, -2.1432],
[-1.0409, 0.8688],
[-0.2574, -0.7791],
[-0.3709, 0.0720],
[-0.3341, -1.4090],
[-0.4335, 0.0161],
[-1.6925, -1.0660],
[-0.6319, -0.7785],
[ 0.7173, -1.3587],
[ 0.2070, -0.1110]]), tensor([[ 9.0409],
[-0.8439],
[ 6.3505],
[ 3.1964],
[ 8.3154],
[ 3.2932],
[ 4.4270],
[ 5.5967],
[10.2503],
[ 4.9808]])]
epoch 1, loss 0.000237
epoch 2, loss 0.000098
epoch 3, loss 0.000097