动手学深度学习(九+)——softmax分类Fashion-MNIST数据集

文章目录

    • 一、Fashion-MNIST数据集
      • 1.1 认识数据集
      • 1.2 小批量读取数据
    • 二、softmax回归从零开始实现
      • 2.1 初始化模型参数
      • 2.2 定义softmax函数及网络模型
      • 2.3 定义交叉熵损失函数
      • 2.4 训练数据
      • 2.5 测试模型
    • 三、使用pytorch简单地实现softmax回归

jupyter编程,更改为pytho脚本请自行修改。整体基于李沐老师的动手学习深度学习-pytorch 2021版。下面是个人模仿代码和笔记,主要用于个人复习,如有错误请告知。

一、Fashion-MNIST数据集

Fashion-MNIST:替代MNIST手写数字集的图像数据集

1.1 认识数据集

导入包

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

下载或导入数据:

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,
)

可视化数据(沐神有提供其他的绘图脚本,但我自己写了一个简单的)

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

fig, ax = plt.subplots(
    nrows=3,
    ncols=4,
    sharex=True,
    sharey=True, )

ax = ax.flatten()

for i in range(12):
    # 只查看了前面12张图片
    img = mnist_train.data[i]
    ax[i].imshow(img)
    ax[i].set(title=get_fashion_mnist_labels(mnist_train[i][1]))

ax[0].set_xticks([])
ax[0].set_yticks([])
plt.tight_layout()
plt.show()

动手学深度学习(九+)——softmax分类Fashion-MNIST数据集_第1张图片

1.2 小批量读取数据

batch_size = 256

def get_dataloader_workers():
    """使用四个进程读取数据"""
    return 4

train_iter = data.DataLoader(mnist_train,batch_size,shuffle=True,
                            num_workers=get_dataloader_workers())
def load_data_fashion_mnist(batch_size,resize=None):
    """下载Fashion-MNIST数据集,并将其保存至内存中"""
    trans = [transforms.ToTensor()]
    if resize:
        trans.insert(0,transforms.Resize(resize)) # transforms.Resize将图片最小的一条边缩放到指定大小,另一边缩放对应比例
    trans = transforms.Compose(trans) # compose用于串联多个操作
    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=True,
                          num_workers = get_dataloader_workers()))

二、softmax回归从零开始实现

2.1 初始化模型参数

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

batch_size = 256
train_iter,test_iter = load_data_fashion_mnist(batch_size)

num_inputs = 784 #图片大小为28*28 
num_outputs = 10 # 分为10类

W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True) # 初始化权重
b = torch.zeros(num_outputs, requires_grad=True) # 初始偏置为0

2.2 定义softmax函数及网络模型

def softmax(X):
    """softmax函数"""
    X_exp = torch.exp(X)
    partition = X_exp.sum(1,keepdim=True) # 按行求和,得一列
    return X_exp/partition

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

2.3 定义交叉熵损失函数

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

2.4 训练数据

def updater(batch_size):
	"""sgd 小批量梯度下降更新"""
    return d2l.sgd([W, b], lr, batch_size)
    
def train_epoch(net, train_iter, loss, updater):  #@save
    """训练模型一个迭代周期"""
    # 将模型设置为训练模式
    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.backward()
            updater.step()
            metric.add(
                float(l) * len(y), accuracy(y_hat, y),
                y.size().numel())
        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]

def train(net, train_iter, test_iter, loss, num_epochs, updater):  #@save
    """训练模型"""
    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(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
num_epochs = 100
train(net, train_iter, test_iter, cross_entropy, num_epochs, updater)

动手学深度学习(九+)——softmax分类Fashion-MNIST数据集_第2张图片

2.5 测试模型

def predict(net, test_iter, n=6):  #@save
    """预测标签"""
    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(net, test_iter)

动手学深度学习(九+)——softmax分类Fashion-MNIST数据集_第3张图片

三、使用pytorch简单地实现softmax回归

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

# 根据批次加载数据,可以使用d2l中的函数,也可以使用上面自定义的
batch_size = 256
train_iter,test_iter = 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()
# 定义梯度更新函数
trainer = torch.optim.SGD(net.parameters(),lr=0.01)

# 训练数据
num_epochs = 100
d2l.train_ch3(net,train_iter,test_iter,loss,num_epochs,trainer)

动手学深度学习(九+)——softmax分类Fashion-MNIST数据集_第4张图片

你可能感兴趣的:(动手学深度学习:pytorch,softmax,pytorch,回归模型,李沐动手学深度学习,神经网络)