本文基于torch实现,用于个人复习并记录学习历程,适用于初学者
个人觉得重要的地方会详细介绍,其他地方略过,只给出代码
目录
从零开始实现
生成数据集
我们将根据带有噪声的线性模型构造一个人造数据集。我们的任务是使用这个有限样本的数据集来恢复这个模型的参数。 我们将使用低维数据,这样可以很容易地将其可视化。 在下面的代码中,我们生成一个包含1000个样本的数据集, 每个样本包含从标准正态分布中采样的2个特征。 我们的合成数据集是一个矩阵𝑋∈𝑅1000×2。
我们使用线性模型参数𝑤=[2,−3.4]⊤、𝑏=4.2 和噪声项𝜖生成数据集及其标签:𝑦=𝑋𝑤+𝑏+𝜖
𝜖可以视为模型预测和标签时的潜在观测误差。 在这里我们认为标准假设成立,即𝜖服从均值为0的正态分布。 为了简化问题,我们将标准差设为0.01。 下面的代码生成合成数据集。
import random #为了随机读取数据
import torch
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, 5000)
import matplotlib.pyplot as plt #可视化
plt.scatter(features[:, 0].detach().numpy(), labels.detach().numpy(), 1)
plt.scatter(features[:, 1].detach().numpy(), labels.detach().numpy(), 1)
可以看到label和feature确实有线性关系。
读取数据集
定义一个函数,打乱数据集并以小批量方式获取数据。
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_size,每次的切片是从i到i+batch_size-1
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
定义模型
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_()
训练
记住三个步骤:
- 通过调用
net(X)
生成预测并计算损失l
(前向传播)。 - 通过进行反向传播来计算梯度。
- 通过调用优化器来更新模型参数。
lr = 0.005
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)
l.sum().backward()
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}')
#输出:
#epoch 1, loss 0.111676
#epoch 2, loss 0.000810
#epoch 3, loss 0.000055
print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差: {true_b - b}')
# w的估计误差: tensor([ 9.5844e-05, -3.6263e-04], grad_fn=<SubBackward0>)
# b的估计误差: tensor([3.6240e-05], grad_fn=<RsubBackward1>)
利用机器学习框架来实现
生成数据集
在这部分如果有利用框架来实现的我会附上与手工实现的代码,让区别更加明显。
import numpy as np
import torch
def synthetic_data(w, b, num_examples): #@save
"""生成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)
读取数据集
现在不用random了,用torch.utils来读取数据
from torch.utils import data
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)
# 附上之前的代码做对比
# 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]
load_array接收的参数中有一个是is_train,这个参数为真即可表示给出的是训练数据集,这样便需要打乱数据,而测试数据集是不需要乱的。
batch_size = 10
data_iter = load_array((features, labels), batch_size)
next(iter(data_iter)) #一次会给出十个数据
定义模型
from torch import nn
net = nn.Sequential(nn.Linear(2, 1))
# def linreg(X, w, b):
# """线性回归模型"""
# return torch.matmul(X, w) + b
初始化模型参数
net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)
# w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)
# b = torch.zeros(1, requires_grad=True)
# w,b
#输出:
#Parameter containing:
#tensor([[-0.0070, -0.0016]], requires_grad=True)
#Parameter containing:
#tensor([0.], requires_grad=True)
定义损失函数
均方误差 mean square error MSE
loss = nn.MSELoss()
定义优化算法
随机梯度下降法 stochastic gradient descent SGD
trainer = torch.optim.SGD(net.parameters(), lr=0.03)
训练
记住三个步骤:
- 通过调用
net(X)
生成预测并计算损失l
(前向传播)。 - 通过进行反向传播来计算梯度。
- 通过调用优化器来更新模型参数。
num_epochs = 4
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}')
# 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()
# 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}')
查看误差
w = net[0].weight.data
print('w的估计误差:', true_w - w.reshape(true_w.shape))
b = net[0].bias.data
print('b的估计误差:', true_b - b)
往期推荐: