【d2l】3.5-7.softmax回归实现

【d2l】3.5-7.softmax回归实现

图像分类数据集

这一部分采用Fashion-MNIST数据集,以衣装为主体,数据是28×28的位图

读取数据集

先用框架内置的函数下载并读取Fashion-MNIST数据集

trans = transforms.ToTensor() # 通过ToTensor实例将PIL转化为float32

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 = False
)

接着看一下一些具体的数值

len(mnist_train), len(mnist_test)
mnist_train[0][0].shape

得到

(60000, 10000)
torch.Size([1, 28, 28])

该数据集包含10个类别,需要先写个函数把数字索引转化为对应的文本名称

def get_fashion_mnist_labels(labels):
    """返回Fashion-MNIST数据集的文本标签"""
    text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
                   'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
    return [text_labels[int(i)] for i in labels]

然后创建一个函数来可视化这些样本

def show_images(imgs, num_rows, num_cols, titles = None, scale = 1.5):
    """绘制图像列表"""
    figsize = (num_cols * scale, num_rows * scale)
    _, axes = plt.subplots(num_rows, num_cols, figsize = figsize)
    axes = axes.flatten()

    for i, (ax, img) in enumerate(zip(axes, imgs)):
        if torch.is_tensor(img):
            ax.imshow(img.numpy())
        else:
            ax.imshow(img)
        ax.axes.get_xaxis().set_visible(False)
        ax.axes.get_yaxis().set_visible(False)
        if titles:
            ax.set_title(titles[i])

    return axes

接着可以读取一下可视化数据

X, y = next(iter(data.DataLoader(mnist_train, batch_size = 18)))
d2l.show_images(X.reshape(18, 28, 28), 2, 9, titles = d2l.get_fashion_mnist_labels(y))

读取小批量

通过随机打乱样本来均匀地读取小批量数据

batch_size = 256

train_iter = data.DataLoader(mnist_train, batch_size, shuffle = True,
                             num_workers = 0)

本来workers数量为4,但是这是linux系统下的要求,windows下只能指定workers为0了

看一下读取训练数据所需的时间

timer = d2l.Timer()
for X, y in train_iter:
    continue
f'{timer.stop() : .2f} sec'
' 1.59 sec'

整合所有组件

下面定义一个load_data_fashion_mnist函数,用于获取和读取Fasion-MNIST数据集,用于返回训练集和数据集的数据迭代器。另外这个函数还可以接收一个resize函数来调整图像形状

def load_data_fashion_mnist(batch_size, resize = None):
    """下载Fashion-MNIST数据集,然后将其加载到内存中"""
    trans = [transforms.ToTensor()]

    if resize:
        trans.insert(0, transforms.Resize(resize))
    
    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 = get_dataloader_workers()),
            data.DataLoader(mnist_test, batch_size, shuffle = False,
                            num_workers = get_dataloader_workers()))

下面通过resize测试一下功能

train_iter, test_iter = d2l.load_data_fashion_mnist(32, resize = 64)
for X, y in train_iter:
    print(X.shape, X.dtype, y.shape, y.dtype)
    break
torch.Size([32, 1, 64, 64]) torch.float32 torch.Size([32]) torch.int64

softmax回归从零实现

首先设置一下批量大小为256,读取一下迭代器

batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

接着初始化参数,输入为784,输出为10,权重会构成一个784×10的矩阵,偏置是1×10的行向量

初始化用正态分布赋值权重参数,用0赋值偏置

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)

实现softmax操作

先确定一下dim=0/1分别是对什么求和

X = torch.tensor([[1., 2., 3.], [4., 5., 6.]])
X.sum(0, keepdim = True), X.sum(1, keepdim = True)
(tensor([[5., 7., 9.]]),
 tensor([[ 6.],
         [15.]]))

而softmax会对每一行求和,所以代码如下

def softmax(X):
    X_exp = torch.exp(X)
    partition = X_exp.sum(1, keepdim = True)
    return X_exp / partition

测试一下

X = torch.normal(0, 1, (2, 5))
X_prob = softmax(X)
X_prob, X_prob.sum(1)
(tensor([[0.0843, 0.1743, 0.3726, 0.3337, 0.0351],
         [0.3489, 0.1992, 0.0983, 0.1707, 0.1829]]),
 tensor([1.0000, 1.0000]))

定义模型及损失函数

下面的模型用reshape转化成向量

def net(X):
    return softmax(torch.matmul(X.reshape((-1, W.shape[0])), W) + b)

损失函数用交叉熵损失,负对数似然实现

def cross_entropy(y_hat, y):
    return - torch.log(y_hat[range(len(y_hat)), y])

cross_entropy(y_hat, y)
tensor([2.3026, 0.6931])

分类精度

从分类问题中,我们需要增加接口,用精确度来评估模型的准确程度

def accuracy(y_hat, y):
    """计算预测正确的数量"""
    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())

另外对于任意数据迭代器data_iter可访问的数据集评估精度

class Accumulator:
    """在n个变量上累加"""
    def __init__(self, n):
        self.data = [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.] * len(self.data)
    
    def __getitem__(self, idx):
        return self.data[idx]

这个Accumulator类用于对多个变量进行累加,后续可复用

def evaluate_accuracy(net, data_iter):
    """计算在指定数据集上模型的精度"""
    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]

训练

先写个Animator用于追踪曲线的变化状态

class Animator:
    """在动画中绘制数据"""
    def __init__(self, xlabel = None, ylabel = None, legend = None,
                 xlim = None, ylim = None,
                 xscale = 'linear', yscale = 'linear',
                 fmts = ('-', 'm--', 'g-.', 'r:'), nrows = 1, ncols = 1,
                 figsize = (3.5, 2.5)):
        # 增量地绘制多条曲线
        if legend is None:
            legend = []
        
        use_svg_display()

        self.fig, self.axes = plt.subplots(nrows, ncols, figsize = figsize)

        if ncols * nrows == 1:
            self.axes = [self.axes, ]
        
        # 使用lambda捕获函数
        self.config_axes = lambda: set_axes(
            self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend
        )

        self.X, self.Y, self.fmts = None, None, fmts

    def add(self, x, y):
        # 向图表中添加多个数据点
        if not hasattr(y, "__len__"):
            y = [y]
        n = len(y)

        if not hasattr(x, '__len__'):
            x = [x] * n
        if not self.X:
            self.X = [[] for _ in range(n)]
        if not self.Y:
            self.Y = [[] for _ in range(n)]
        
        for i, (a, b) in enumerate(zip(x, y)):
            if a is not None and b is not None:
                self.X[i].append(a)
                self.Y[i].append(b)
        self.axes[0].cla()

        for x, y, fmt in zip(self.X, self.Y, self.fmts):
            self.axes[0].plot(x, y, fmt)
        self.config_axes()

        display.display(self.fig)
        display.clear_output(wait = True)

接着写个训练一个epoch的函数

def train_epoch_ch3(net, train_iter, loss, updater):
    """训练模型一轮"""
    # 将模型设置为训练模式

    if isinstance(net, torch.nn.Module):
        net.train()
    
    # 训练损失总和、训练准确度总和、样本数
    metric = Accumulator(3)

    for X, y in train_iter:
        # 计算梯度并更新参数
        y_hat = net(X)
        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]

最后实现一个训练函数,它在train_iter访问的训练数据集上训练一个模型net,利用test_iter评估

def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):
    """训练模型"""
    animator = Animator(xlabel = 'epoch', xlim = [1, num_epochs], ylim = [0.3, 0.9],
                        legend = ['train loss', 'train acc', 'test acc'])
    
    for epoch in range(num_epochs):
        train_metrics = train_epoch_ch3(net, train_iter, loss, updater)
        test_acc = evaluate_accuracy(net, test_iter)
        animator.add(epoch + 1, train_metrics + (test_acc, ))
    
    train_loss, train_acc = train_metrics

    assert train_loss < 0.5, train_loss
    assert train_acc <= 1 and train_acc > 0.7, train_acc
    assert test_acc <= 1 and test_acc > 0.7, test_acc
lr = 0.1

def updater(batch_size):
    return d2l.sgd([W, b], lr, batch_size)

num_epochs = 10
d2l.train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)

训练出来的曲线如下

预测

写一个预测函数,目前模型已经实现了分类,给定一定数量的样本,显示实际标签和对应预测

def predict_ch3(net, test_iter, n = 6):
    """预测标签"""
    for X, y in test_iter:
        break

    trues = get_fashion_mnist_labels(y)
    preds = get_fashion_mnist_labels(net(X).argmax(axis = 1))

    titles = [true + '\n' + pred for true, pred in zip(trues, preds)]
    show_images(
        X[0:n].reshape((n, 28, 28)), 1, n, titles = titles[0:n]
    )
    
d2l.predict_ch3(net, test_iter)

softmax简洁实现

下面将全部用内置接口实现,以下是完整代码

import torch
from torch import nn

import sys
sys.path.append('../')
from d2l_local import torch as d2l

batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

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)

loss = nn.CrossEntropyLoss(reduction = 'none')

trainer = torch.optim.SGD(net.parameters(), lr = 0.1)

num_epochs = 10
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)

训练结果和前一种相似

其中需要重新审视一下softmax实现,事实上假如\(o_j\)的数值特别大的话,可能导致精度不够从而softmax值为0,为了避免这种情况,会让所有的\(o_j \leftarrow o_j - \max\{ o_k \}\)

从而

\[\begin{aligned} \log \hat{y_j} &= \log \frac{\exp(o_j -\max \{o_k\})}{\sum_k \exp (o_k - \max\{ o_k \})} \\ &= o_j - \max\{ o_k \} - \log \sum_k \exp(o_k - \max\{ o_k \}) \end{aligned} \]

posted @ 2026-02-05 18:16  R4y  阅读(1)  评论(0)    收藏  举报