【动手学习pytorch笔记】2.softmax回归

图像分类数据集

%matplotlib inline
import torch
import torchvision
from torch.utils import data
from torchvision import transforms
from d2l import torch as d2l

d2l.use_svg_display()

读取数据集

trans = transforms.ToTensor()
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)

len(mnist_train),len(mnist_test)

输出

(60000, 10000)
mnist_train[0][0].shape

输出

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

单通道,28 * 28

def get_fashion_mnist_labels(labels):
    """返回数据集的文本标签"""
    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 = d2l.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)))
show_images(X.reshape(18,28,28), 2, 9, titles=get_fashion_mnist_labels(y));

​ 将数据集放进一个DataLoader里,指定一个batch_size

【动手学习pytorch笔记】2.softmax回归_第1张图片

读取小批量

batch_size = 256

def get_dataloader_workers():  #@save
    """使用4个进程来读取数据"""
    return 4

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

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

输出

'6.63 sec'

整合所有组件

def load_data_fashion_mnist(batch_size, resize=None):  #@save
    """下载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()))

softmax回归的从零开始实现

import torch
from IPython import display
from d2l import torch as d2l

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

每次读取256个图片,返回训练集和测试集迭代器

初始化模型参数

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)

像素 = 28 * 28,通道数 = 1,作为一个向量输入维度 = 784,这个拉伸过程会损失很多空间信息,卷积神经网络可以解决这个问题。
图片有10种分类,所以输出维度 = 10
W矩阵大小 784 * 10 ,计算梯度 requires_grad=True
b是长为10的列向量

定义softmax操作

X = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
X.sum(0, keepdim=True), X.sum(1, keepdim=True)

输出

(tensor([[5., 7., 9.]]),
 tensor([[ 6.],
         [15.]]))

回顾一下:对矩阵某一行或列求和
0:列的求和(把所有行摞到一起)
1:行的求和(把所有列挤到一起)
keepdim = True 保持矩阵的维度

def softmax(X):
    X_exp = torch.exp(X)
    partition = X_exp.sum(1, keepdim=True)
    return X_exp / partition  # 这里应用了广播机制

s o f t m a x ( X ) i j = e x p ( X i j ) ∑ k e x p ( X i k ) softmax(X)_{ij} = \frac{exp(X_{ij})}{\sum_{k}exp(X_{ik})} softmax(X)ij=kexp(Xik)exp(Xij)

对于输出矩阵,对每一行(每一个样本)做Softmax

验证一下

X = torch.normal(0, 1, (2, 5))
X_prob = softmax(X)
X_prob, X_prob.sum(1)

输出

(tensor([[0.2459, 0.0962, 0.1512, 0.4693, 0.0374],
         [0.1013, 0.0931, 0.1746, 0.0606, 0.5704]]),
 tensor([1., 1.]))

定义模型

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

reshape((-1, W.shape[0])) -1:自己算一下,实际等于批量大小。

维度:

​ X = batchsize(256) * 样本的长度(784)

​ W = 784 * 10

​ b = 10 * 1

构建损失函数

怎么把预测值拿出来?

y = torch.tensor([0, 2])
y_hat = torch.tensor([[0.1, 0.3, 0.6], 
                      [0.3, 0.2, 0.5]])
y_hat[[0, 1], y]

例子

对两个样本做三个类别的预测:

​ y:正确的分类,即第一个样本应该被预测为第一类,第二个样本应该被预测为第三类。

​ y_hat:我的输出

y_hat[[0, 1], y] : 二维矩阵中元素的位置:[0 , 0],[1 , 2]

​ 即我预测出来的值 0.1和0.5

tensor([0.1000, 0.5000])

交叉熵损失函数

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

cross_entropy(y_hat, y)

range(len(y_hat)):生成 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

tensor([2.3026, 0.6931])

还是上面的那个两个样本的例子,分别求出了两个样本的损失

预测类别与真实y进行比较

def accuracy(y_hat, y):  
    """计算预测正确的数量"""
    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
        """axis=1:每一行的列的值进行比较,最大的作为这一行的y_hat"""
        y_hat = y_hat.argmax(axis=1)
    cmp = y_hat.type(y.dtype) == y
    return float(cmp.type(y.dtype).sum())
accuracy(y_hat, y) / len(y)

cmp是bool值,该函数返回预测正确的样本数,然后计算预测正确率

0.5

评估任意模型net的正确率

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:
            #先预测一下net(X),再评估一下正确率accuracy(net(X), y),放入累加器
            metric.add(accuracy(net(X), y), y.numel())          
    return metric[0] / metric[1]
class Accumulator:  
    """在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]

evaluate_accuracy(net, test_iter)

测试一下

0.086

这时候还没反向传播梯度下降呢,就是一个随机的模型,准确率大概10%,正好10个类别

Softmax回归训练

#训练一带
def train_epoch_ch3(net, train_iter, loss, updater):  
    """训练模型一个迭代周期(定义见第3章)"""
    # 如果我用的是nn,将模型设置为训练模式,告诉pytorch我要计算梯度
    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]
#画图
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 = []
        d2l.use_svg_display()
        self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
        if nrows * ncols == 1:
            self.axes = [self.axes, ]
        # 使用lambda函数捕获参数
        self.config_axes = lambda: d2l.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)
def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):  #@save
    """训练模型(定义见第3章)"""
    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
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)

【动手学习pytorch笔记】2.softmax回归_第2张图片

预测

def predict_ch3(net, test_iter, n=6):  #@save
    """预测标签(定义见第3章)"""
    for X, y in test_iter:
        break
    trues = d2l.get_fashion_mnist_labels(y)
    preds = d2l.get_fashion_mnist_labels(net(X).argmax(axis=1))
    titles = [true +'\n' + pred for true, pred in zip(trues, preds)]
    d2l.show_images(
        X[0:n].reshape((n, 28, 28)), 1, n, titles=titles[0:n])

predict_ch3(net, test_iter)

【动手学习pytorch笔记】2.softmax回归_第3张图片

Sofrmax的简洁实现

import torch
from torch import nn
from d2l import torch as d2l

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

初始化模型参数

# 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);

因为softmax不会调整形状,所以nn.Flatten():将任意维度压缩成二维,保留第一个维度(样本数),将剩下的维度拉伸成一个变量。和reshape()差不多。

后面一个线性层,输入:784;输出:10

init_weights(m) : m是当前层,如果是线性层,把w初始化成均值为0,方差为1的正态分布随机值。

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)

​ 之前在d2l中保存的 train_ch3

【动手学习pytorch笔记】2.softmax回归_第4张图片

你可能感兴趣的:(pytorch学习笔记,pytorch,深度学习)