天天看點

pytorch學習(九+)——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()
           
pytorch學習(九+)——softmax分類Fashion-MNIST資料集

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)
           
pytorch學習(九+)——softmax分類Fashion-MNIST資料集

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)
           
pytorch學習(九+)——softmax分類Fashion-MNIST資料集

三、使用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)

           
pytorch學習(九+)——softmax分類Fashion-MNIST資料集

繼續閱讀