[pytorch] 從易到難解決 MNIST 問題

MNIST

MNIST 可謂是機器學習的入門必講的問題了。MNIST 數據集包含了手寫的 0-9 的圖片,其中有一個訓練數據集和一個測試數據集。本文就採用「從易到難」的三種不一樣的模型,不斷提高機器學習的正確率。html

由於文章跨度較大,因此關於 pytorch 的基礎內容在本文中不會介紹。基礎內容能夠參考 pytorch入門python

1. Logistic Regression (邏輯迴歸)

Logistic Regression(邏輯迴歸)是用於解決分類問題的中很是經常使用的手段,而 MNIST 正好就是一個分類問題。 因此第一個要介紹的就是邏輯迴歸模型。網絡

關於邏輯迴歸的原理和介紹,能夠參考 邏輯迴歸(logistic regression)的本質機器學習

首先先要構造模型,由於輸入的圖片大小爲 28*28 ,而最終分類完成後輸出 10 種結果,因此咱們先用 nn.Linear(28 * 28, 10) 建立一個全鏈接層。函數

模型建立成功後,咱們還要編寫訓練與測試的函數,其中使用預置好的 nn.CrossEntropyLoss() (交叉熵損失)函數來計算損失,使用 optim.SGD() (隨機梯度降低法)來進行優化。學習

from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torchvision import datasets, transforms


class logistic(nn.Module):
    def __init__(self):
        super(logistic, self).__init__()
        self.logstic = nn.Linear(28 * 28, 10)

    def forward(self, x):
        out = self.logstic(x)
        return out


def train(model, device, train_loader, optimizer, epoch):
    model.train()
    criterion = nn.CrossEntropyLoss()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        data = Variable(data.view(-1, 28 * 28))
        target = Variable(target)
        optimizer.zero_grad()
        output = model(data)
        loss = criterion(output, target)
        loss.backward()
        optimizer.step()
        if batch_idx % log_interval == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))


def test(model, device, test_loader):
    criterion = nn.CrossEntropyLoss()
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            data = Variable(data.view(-1, 28 * 28))
            target = Variable(target)
            output = model(data)
            # get the index of the max log-probability
            pred = output.max(1, keepdim=True)[1]
            correct += pred.eq(target.view_as(pred)).sum().item()

    print('\nTest set:  Accuracy: {}/{} ({:.0f}%)\n'.format(
        correct,
        len(test_loader.dataset),
        100. * correct / len(test_loader.dataset))
    )


if __name__ == '__main__':
    batch_size = 64
    test_batch_size = 1000
    epochs = 10
    lr = 0.01
    momentum = 0.5
    seed = 1
    log_interval = 32

    use_cuda = torch.cuda.is_available()

    torch.manual_seed(seed)

    device = torch.device("cuda" if use_cuda else "cpu")

    kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
    train_loader = torch.utils.data.DataLoader(
        datasets.MNIST('./data', train=True, download=True,
                       transform=transforms.Compose([
                           transforms.ToTensor(),
                           transforms.Normalize((0.1307,), (0.3081,))
                       ])),
        batch_size=batch_size, shuffle=True, **kwargs)
    test_loader = torch.utils.data.DataLoader(
        datasets.MNIST('./data', train=False, transform=transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize((0.1307,), (0.3081,))
        ])),
        batch_size=test_batch_size, shuffle=True, **kwargs)

    model = logistic().to(device)
    optimizer = optim.SGD(model.parameters(), lr=lr,
                          momentum=momentum)

    for epoch in range(1, epochs + 1):
        train(model, device, train_loader, optimizer, epoch)
        test(model, device, test_loader)

進行了十輪訓練後,最終的正確率大約達到了 92% 。測試

logistic-result

雖然做爲最簡單的示例,這個結果看起來還比較可觀了。不過做爲一個只須要識別數字的問題,這樣的準確率仍是遠遠不夠的。優化

2. Multilayer Neural Network (多層神經網絡)

在上一個模型,咱們定義時用到了 nn.Linear() 這個函數,它的做用時構造一個全鏈接層。也就是說,邏輯迴歸的模型,其實就是一個簡單的單層網絡。.net

class logistic(nn.Module):
    def __init__(self):
        super(logistic, self).__init__()
        self.logstic = nn.Linear(28 * 28, 10)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        x = self.logstic(x)
        out = self.sigmoid(x)
        return out

能夠看到,它將 28*28 的輸入最終鏈接到 10 種輸出,這樣的確十分簡單,可是擬合度就不夠了。爲了讓正確率更高,咱們須要多層網絡來更好地進行分類。code

神經網絡的層數不是越多越好,層數變多容易形成「過擬合」,反而致使準確率降低。

這裏咱們就建立三層神經網絡,讓前一層的輸出做爲後一層的輸入。

class net(nn.Module):
    def __init__(self):
        super(net, self).__init__()
        self.layer1 = nn.Linear(28 * 28, 300)
        self.layer2 = nn.Linear(300, 100)
        self.layer3 = nn.Linear(100, 10)

    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        return x

這樣一個網絡其實可以運行了,可是咱們還須要添加批標準化 BatchNorm1d() 與激活函數 ReLU() ,來增長網絡的收斂速度和非線性,最終代碼以下。要注意的是,最後一個輸出層不須要添加函數。

class net(nn.Module):
    def __init__(self):
        super(net, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Linear(28 * 28, 300),
            nn.BatchNorm1d(300),
            nn.ReLU(True))
        self.layer2 = nn.Sequential(
            nn.Linear(300, 100),
            nn.BatchNorm1d(100),
            nn.ReLU(True))
        self.layer3 = nn.Sequential(
            nn.Linear(100, 10))

    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        return x

將這段代碼替換掉原有的 logistic 類,就能夠運行了。要注意在修改以後,要將程序中靠近末尾的 model = logistic().to(device) 改成 model = net().to(device) ,否則會報錯。

MNN-result

能夠看到準確度達到了 98% ,多層網絡的提高仍是很明顯的。不過圖像領域,多層神經網絡並非最好的選擇。 CNN 模型的完善,給計算機視覺領域帶來了突破性的發展。

3. CNN (卷積神經網絡)

以上的神經網絡,一張只有 28*28 的灰度圖在第一層就須要 784 個神經元。若是圖像更大,還包含 RGB 三通道,那麼數據量就會更龐大。這個時候, CNN 就體現出它的優點了。關於 CNN 的原理與歷史,本文就再也不詳細介紹。若是有興趣能夠參考這篇文章: 卷積神經網絡(CNN)模型結構

pytorch 中,只須要使用 nn.Conv2d() 就能夠建立一個卷積層。咱們的目標就是建立一個標準的 CNN 結構:

CNN-structure

在每次卷積後,咱們都須要對其進行池化,防止數據量過多。由於這裏沒有使用 Variable ,咱們使用 F.nll_loss() (可能損失負對數)函數來評估損失。關於這些函數的用法,你們能夠自行搜索一下。由於代碼與上面的有幾個地方不一樣,因此這裏直接貼出來:

from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms


class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
        self.conv2_drop = nn.Dropout2d()
        self.layer1 = nn.Sequential(
            nn.Linear(320, 100),
            nn.BatchNorm1d(100),
            nn.ReLU(True))
        self.layer2 = nn.Sequential(
            nn.Linear(100, 10))

    def forward(self, x):
        x = F.relu(F.max_pool2d(self.conv1(x), 2))
        x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
        x = x.view(-1, 320)
        x = self.layer1(x)
        x = F.dropout(x, training=self.training)
        x = self.layer2(x)
        return F.log_softmax(x, dim=1)


def train(model, device, train_loader, optimizer, epoch):
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()
        if batch_idx % log_interval == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))


def test(model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            # get the index of the max log-probability
            pred = output.max(1, keepdim=True)[1]
            correct += pred.eq(target.view_as(pred)).sum().item()

    print('\nTest set:  Accuracy: {}/{} ({:.0f}%)\n'.format(
        correct,
        len(test_loader.dataset),
        100. * correct / len(test_loader.dataset))
    )


if __name__ == '__main__':
    batch_size = 64
    test_batch_size = 1000
    epochs = 10
    lr = 0.01
    momentum = 0.5
    seed = 1
    log_interval = 32

    use_cuda = torch.cuda.is_available()

    torch.manual_seed(seed)

    device = torch.device("cuda" if use_cuda else "cpu")

    kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
    train_loader = torch.utils.data.DataLoader(
        datasets.MNIST('./data', train=True, download=True,
                       transform=transforms.Compose([
                           transforms.ToTensor(),
                           transforms.Normalize((0.1307,), (0.3081,))
                       ])),
        batch_size=batch_size, shuffle=True, **kwargs)
    test_loader = torch.utils.data.DataLoader(
        datasets.MNIST('./data', train=False, transform=transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize((0.1307,), (0.3081,))
        ])),
        batch_size=test_batch_size, shuffle=True, **kwargs)

    model = CNN().to(device)
    optimizer = optim.SGD(model.parameters(), lr=lr,
                          momentum=momentum)

    for epoch in range(1, epochs + 1):
        train(model, device, train_loader, optimizer, epoch)
        test(model, device, test_loader)

運行以後,能夠看到,正確率達到了 99% ,不過用時相對也更多了。

CNN-result

若是觀察每一個流程,能夠發如今準確率加到 97% 以後,訓練提高的速度就會變得很慢。不過這個只是最基礎的 CNN 模型,其餘還有許多拓展模型,好比 AlexNet , GoogLeNet 等等。這些模型在處理 MNIST 問題時能夠達到接近 100% 的正確率。若是你們感興趣能夠去了解一下。

結語與其餘文檔

這樣,咱們就經過 MNIST 這一個問題,介紹了三種不一樣的解答方法,其實這也是計算機視覺領域的進化史。在 CNN 模型之上,也有更加完善、高效的模型。但願你們可以在以後的學習中瞭解它們,而且作出更好玩的項目。

相關文章
相關標籤/搜索