import random
import torch
from d2l import torch as d2l
# 根据带有噪声的线性模型构造一个人造数据集
def synthetic_data(w, b, num_examples):
"""生成 y = Wx + b + 噪声"""
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 = synthetic_data(true_w, true_b, 1000)
print('features:', features[0], '\nlabel:', labels[0])
# 绘制表格
d2l.set_figsize()
d2l.plt.scatter(features[:, 1].detach().numpy(), labels.detach().numpy(), 1)
# 定义一个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_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): # 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 # 之前的损失函数没有求均值,所以此处除以batch_size
param.grad.zero_() # 梯度设置为0,使得下一次计算时与上次计算无关
# 训练过程
lr = 0.03 # learning rate
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),而不是一个标量。l中的所有元素被加到一起
# 并以此计算关于[w, b]的梯度
l.sum().backward()
sgd([w, b], lr, batch_size) # 使用参数的梯度更新
with torch.no_grad(): # 评价时不需要计算梯度z
train_l = loss(net(features, w, b), labels)
print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')
# with torch.no_grad()对于require_grad设置为True的tensor计算操作,是构建计算图的(计算过程的构建,以便梯度反向传播等操作)
# 但并非所有的操作都需要计算图的生成,使用该语句可以强制之后的内容不构建计算图
# 即使得所有tensor的require_grad自动设置为False
# with工作原理:
# 紧跟with后面的语句被求值后,返回对象的“–enter–()”方法被调用,这个方法的返回值将被赋值给as后面的变量
# 当with后面的代码块全部被执行完之后,将调用前面返回对象的“–exit–()”方法
features: tensor([ 1.5298, -0.0633])
label: tensor([7.4758])
tensor([[-0.4639, 0.7517],
[-0.9761, -0.9253],
[ 0.0324, -0.4125],
[-0.1293, -0.1273],
[ 1.2964, 0.1398],
[-0.1523, 0.2854],
[ 0.3366, -0.5548],
[ 0.5532, -0.7408],
[ 1.5298, 0.5990],
[-0.1460, 1.1620]])
tensor([[ 0.7178],
[ 5.3872],
[ 5.6876],
[ 4.3913],
[ 6.3321],
[ 2.9196],
[ 6.7500],
[ 7.8243],
[ 5.2248],
[-0.0137]])
epoch 1, loss 0.031538
epoch 2, loss 0.000113
epoch 3, loss 0.000052
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)
def load_array(data_arrays, batch_size, is_train=True):
"""构造一个PyTorch数据迭代器"""
dataset = data.TensorDataset(*data_arrays) # dataset拿到数据集
return data.DataLoader(dataset, batch_size, shuffle=is_train) # DataLoader从中挑选样本出来
batch_size = 10
data_iter = load_array((features, labels), batch_size)
print(next(iter(data_iter))) # 通过next得到X和y
# 使用框架的预定义好的层
# nn是神经网络的缩写
from torch import nn
net = nn.Sequential(nn.Linear(2, 1)) # 2,1分别指的是输入维度和输出维度;Sequential是一个list of layers,是一个容器
# 初始化模型参数
net[0].weight.data.normal_(0, 0.01) # 使用正态分布来替换掉data的值
net[0].bias.data.fill_(0)
# 计算局方误差使用的是MSELoss类,也称为平方范数
loss = nn.MSELoss()
# 实例化SGD实例
trainer = torch.optim.SGD(net.parameters(), lr=0.03) # SGD在名为optimizer的module里面;net.parameters()包括了w和b
# 训练过程
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() # step进行模型的更新,即分别更新权重和偏差
l = loss(net(features), labels)
print(f'epoch {epoch + 1}, loss {l:f}')
[tensor([[-0.3531, -0.2199],
[-0.8259, -0.6773],
[ 0.0967, 0.0304],
[-0.4814, -0.9995],
[-1.5095, 0.3725],
[-1.4702, 1.9153],
[ 1.4900, 0.3487],
[-0.1075, -1.8635],
[ 0.7835, -0.3447],
[-1.6065, 0.1877]]), tensor([[ 4.2669],
[ 4.8659],
[ 4.2777],
[ 6.6346],
[-0.0717],
[-5.2570],
[ 5.9959],
[10.3357],
[ 6.9295],
[ 0.3451]])]
epoch 1, loss 0.000195
epoch 2, loss 0.000097
epoch 3, loss 0.000097
|