2024.01.09 softmax回归
因为学习大模型的微调遇到了障碍,所以回头再快速看一遍深度学习的原理。都是一些基础内容。。。
https://zh.d2l.ai/chapter_linear-networks/softmax-regression.html
softmax回归原理
softmax的目的是保证在任何数据上的输出都是非负的且总和为1。因为概率总是非负的,但是模型的输出具有多样性,可能是负数,所以在分类模型时,通常在神经网络的最后一层加上softmax层,保证输出为正,且输出的总和为1。
1 softmax回归模型
softmax的公式如下:
y
^
=
softmax
(
o
)
其中
y
^
j
=
exp
(
o
j
)
∑
k
exp
(
o
k
)
\hat{\mathbf{y}}=\text{softmax}(\mathbf{o})\quad\text{其中}\quad\hat{y}_j=\frac{\exp(o_j)}{\sum_k\exp(o_k)}
y^=softmax(o)其中y^j=∑kexp(ok)exp(oj)
2 损失函数
softmax的损失函数是:损失函数是由最大似然估计和对数似然推导的,详情可以看《动手学深度学习》一书,这里就没必要推导了。也比较简单。
l
(
y
,
y
^
)
=
−
∑
j
=
1
q
y
j
log
y
^
j
l(\mathbf{y},\hat{\mathbf{y}})=-\sum_{j=1}^{q}y_{j}\log\hat{y}_{j}
l(y,y^)=−j=1∑qyjlogy^j
这个损失函数也通常叫做交叉熵损失(cross-entropy loss)。
其梯度是真实概率和预测概率之间的差值:
∂
o
i
l
(
y
,
y
^
)
=
softmax
(
o
)
i
−
y
i
\partial_{o_i}l(\mathbf{y},\mathbf{\hat{y}})=\text{softmax}(\mathbf{o})_i-y_i
∂oil(y,y^)=softmax(o)i−yi
softmax回归从零开始实现
1 构造数据集
import torch
import torchvision
from torch.utils import data
from torchvision import transforms
def load_data_fashion_mnist(batch_size, resize=None): #@save
"""下载Fashion-MNIST数据集,然后将其加载到内存中"""
#通过ToTensor实例将图像数据从PIL类型变换成32位浮点数格式,并除以255使得所有像素的数值均在0~1之间
trans = [transforms.ToTensor()]
if resize:
# transforms.Resize(256)调整图像大小到 256x256 像素
trans.insert(0, transforms.Resize(resize))
#当你需要对图像进行一系列预处理步骤时,transforms.Compose 允许你以一种简洁和模块化的方式来堆叠这些变换。
trans = transforms.Compose(trans)
mnist_train = torchvision.datasets.FashionMNIST(
root="./data", train=True, transform=trans, download=True)
mnist_test = torchvision.datasets.FashionMNIST(
root="./data", train=False, transform=trans, download=True)
return (data.DataLoader(mnist_train, batch_size, shuffle=True,
num_workers=4),
data.DataLoader(mnist_test, batch_size, shuffle=False,
num_workers=4))
train_iter, test_iter = load_data_fashion_mnist(256)
2 初始化模型参数w和b
说明:因为softmax本身不具备训练参数,所以这里的w和b是线性函数的。softmax只是将线性函数的输出转换为概率而已。
num_inputs = 784
num_outputs = 10
W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True)
b = torch.zeros(num_outputs, requires_grad=True)
3 定义softmax回归模型
def softmax(X):
X_exp = torch.exp(X)
partition = X_exp.sum(1, keepdim=True)
return X_exp / partition # 这里应用了广播机制
4 构建神经网络(线性函数+softmax)
def net(X):
return softmax(torch.matmul(X.reshape((-1, W.shape[0])), W) + b)
5 定义损失函数
分类模型常用交叉熵损失
def cross_entropy(y_hat, y):
return - torch.log(y_hat[range(len(y_hat)), y])
6 定义优化算法
lr = 0.1
def sgd(params, lr, batch_size):
"""小批量随机梯度下降"""
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_()
def updater(batch_size):
return sgd([W, b], lr, batch_size)
7 定义准确率计算函数
def accuracy(y_hat, y): #@save
"""计算预测正确的数量"""
if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
y_hat = y_hat.argmax(axis=1)
cmp = y_hat.type(y.dtype) == y
return float(cmp.type(y.dtype).sum())
class Accumulator: #@save
"""在n个变量上累加"""
def __init__(self, n):
self.data = [0.0] * n
def add(self, *args):
self.data = [a + float(b) for a, b in zip(self.data, args)]
def reset(self):
self.data = [0.0] * len(self.data)
def __getitem__(self, idx):
return self.data[idx]
def evaluate_accuracy(net, data_iter): #@save
"""计算在指定数据集上模型的精度"""
if isinstance(net, torch.nn.Module):
net.eval() # 将模型设置为评估模式
metric = Accumulator(2) # 正确预测数、预测总数
with torch.no_grad():
for X, y in data_iter:
metric.add(accuracy(net(X), y), y.numel())
return metric[0] / metric[1]
8 定义模型训练函数
def train_epoch_ch3(net, train_iter, loss, updater):
"""训练模型一个迭代周期(定义见第3章)"""
# 将模型设置为训练模式
if isinstance(net, torch.nn.Module):
net.train()
# 训练损失总和、训练准确度总和、样本数
metric = Accumulator(3)
for X, y in train_iter:
# 计算梯度并更新参数
y_hat = net(X)
# print(y_hat)
l = loss(y_hat, y)
if isinstance(updater, torch.optim.Optimizer):
# 使用PyTorch内置的优化器和损失函数
updater.zero_grad()
l.mean().backward()
updater.step()
else:
# 使用定制的优化器和损失函数
l.sum().backward()
updater(X.shape[0])
metric.add(float(l.sum()), accuracy(y_hat, y), y.numel())
# 返回训练损失和训练精度
return metric[0] / metric[2], metric[1] / metric[2]
9 训练
num_epochs = 10
for epoch in range(num_epochs):
train_metrics = train_epoch_ch3(net, train_iter, cross_entropy, updater)
test_acc = evaluate_accuracy(net, test_iter)
损失和acc
print(train_metrics, test_acc)
输出:
(0.43976358693440754, 0.8502333333333333) 0.8324
softmax回归的简洁实现
1 构造数据集
import torch
import torchvision
from torch.utils import data
from torchvision import transforms
def load_data_fashion_mnist(batch_size, resize=None): #@save
"""下载Fashion-MNIST数据集,然后将其加载到内存中"""
#通过ToTensor实例将图像数据从PIL类型变换成32位浮点数格式,并除以255使得所有像素的数值均在0~1之间
trans = [transforms.ToTensor()]
if resize:
# transforms.Resize(256)调整图像大小到 256x256 像素
trans.insert(0, transforms.Resize(resize))
#当你需要对图像进行一系列预处理步骤时,transforms.Compose 允许你以一种简洁和模块化的方式来堆叠这些变换。
trans = transforms.Compose(trans)
mnist_train = torchvision.datasets.FashionMNIST(
root="./data", train=True, transform=trans, download=True)
mnist_test = torchvision.datasets.FashionMNIST(
root="./data", train=False, transform=trans, download=True)
return (data.DataLoader(mnist_train, batch_size, shuffle=True,
num_workers=4),
data.DataLoader(mnist_test, batch_size, shuffle=False,
num_workers=4))
train_iter, test_iter = load_data_fashion_mnist(256)
2 构建神经网络并初始化模型参数
说明:因为softmax本身不具备训练参数,所以这里的w和b是线性函数的。softmax只是将线性函数的输出转换为概率而已。
from torch import nn
# PyTorch不会隐式地调整输入的形状。因此,
# 我们在线性层前定义了展平层(flatten),来调整网络输入的形状
net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))
def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01)
net.apply(init_weights);
3 定义损失函数
分类模型常用交叉熵损失
loss = nn.CrossEntropyLoss(reduction='none')
4 定义优化算法
trainer = torch.optim.SGD(net.parameters(), lr=0.1)
5 定义准确率计算函数
def accuracy(y_hat, y): #@save
"""计算预测正确的数量"""
if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
y_hat = y_hat.argmax(axis=1)
cmp = y_hat.type(y.dtype) == y
return float(cmp.type(y.dtype).sum())
class Accumulator: #@save
"""在n个变量上累加"""
def __init__(self, n):
self.data = [0.0] * n
def add(self, *args):
self.data = [a + float(b) for a, b in zip(self.data, args)]
def reset(self):
self.data = [0.0] * len(self.data)
def __getitem__(self, idx):
return self.data[idx]
def evaluate_accuracy(net, data_iter): #@save
"""计算在指定数据集上模型的精度"""
if isinstance(net, torch.nn.Module):
net.eval() # 将模型设置为评估模式
metric = Accumulator(2) # 正确预测数、预测总数
with torch.no_grad():
for X, y in data_iter:
metric.add(accuracy(net(X), y), y.numel())
return metric[0] / metric[1]
6 定义模型训练函数
def train_epoch_ch3(net, train_iter, loss, updater):
"""训练模型一个迭代周期(定义见第3章)"""
# 将模型设置为训练模式
if isinstance(net, torch.nn.Module):
net.train()
# 训练损失总和、训练准确度总和、样本数
metric = Accumulator(3)
for X, y in train_iter:
# 计算梯度并更新参数
y_hat = net(X)
# print(y_hat)
l = loss(y_hat, y)
if isinstance(updater, torch.optim.Optimizer):
# 使用PyTorch内置的优化器和损失函数
updater.zero_grad()
l.mean().backward()
updater.step()
else:
# 使用定制的优化器和损失函数
l.sum().backward()
updater(X.shape[0])
metric.add(float(l.sum()), accuracy(y_hat, y), y.numel())
# 返回训练损失和训练精度
return metric[0] / metric[2], metric[1] / metric[2]
7 训练
num_epochs = 10
for epoch in range(num_epochs):
train_metrics = train_epoch_ch3(net, train_iter, loss, trainer)
test_acc = evaluate_accuracy(net, test_iter)
损失和acc
print(train_metrics, test_acc)
输出:
(0.4199913246790568, 0.8566333333333334) 0.8381