深度學習代碼實戰——基於RNN的手寫數字分類

1.前言

循環神經網絡讓神經網絡有了記憶, 對於序列型的數據,循環神經網絡能達到更好的效果.接着我將實戰分析手寫數字的 RNN分類

2.導入模塊、定義超參數

import torch
from torch import nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt


torch.manual_seed(1)    

EPOCH = 1               
BATCH_SIZE = 64
TIME_STEP = 28          
INPUT_SIZE = 28         
LR = 0.01               
DOWNLOAD_MNIST = True  

3.準備訓練數據測試數據

train_data = dsets.MNIST(
    root='./mnist/',
    train=True,                         
    transform=transforms.ToTensor(),   
                                        
    download=DOWNLOAD_MNIST,            
)


print(train_data.data.size())     # (60000, 28, 28)
print(train_data.targets.size())   # (60000)
plt.imshow(train_data.train_data[0].numpy(), cmap='gray')
plt.title('%i' % train_data.train_labels[0])
plt.show()


train_loader = torch.utils.data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)


test_data = dsets.MNIST(root='./mnist/', train=False, transform=transforms.ToTensor())
test_x = test_data.data.type(torch.FloatTensor)[:2000]/255
test_y = test_data.targets.numpy()[:2000]   

在這裏插入圖片描述

4.構建模型並打印模型結構

RNN 整體流程

(input0, state0) -> LSTM -> (output0, state1);
(input1, state1) -> LSTM -> (output1, state2);

(inputN, stateN)-> LSTM -> (outputN, stateN+1);
outputN -> Linear -> prediction. 通過LSTM分析每一時刻的值, 並且將這一時刻和前面時刻的理解合併在一起, 生成當前時刻對前面數據的理解或記憶. 傳遞這種理解給下一時刻分析.

class RNN(nn.Module):
    def __init__(self):
        super(RNN, self).__init__()

        self.rnn = nn.LSTM(         # if use nn.RNN(), it hardly learns
            input_size=INPUT_SIZE,
            hidden_size=64,         # rnn hidden unit
            num_layers=1,           # number of rnn layer
            batch_first=True,       # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size)
        )

        self.out = nn.Linear(64, 10)

    def forward(self, x):
        # x shape (batch, time_step, input_size)
        # r_out shape (batch, time_step, output_size)
        # h_n shape (n_layers, batch, hidden_size)
        # h_c shape (n_layers, batch, hidden_size)
        r_out, (h_n, h_c) = self.rnn(x, None)   # None 表示第0個初始狀態

        
        out = self.out(r_out[:, -1, :])  #取最後一個時間狀態
        return out


rnn = RNN()
print(rnn)

在這裏插入圖片描述

5.損失函數和優化器

optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)   
loss_func = nn.CrossEntropyLoss()  

6.訓練

和以前一樣, 我們用一個 class 來建立 RNN 模型. 這個 RNN 整體流程是

(input0, state0) -> LSTM -> (output0, state1);
(input1, state1) -> LSTM -> (output1, state2);

(inputN, stateN)-> LSTM -> (outputN, stateN+1);
outputN -> Linear -> prediction. 通過LSTM分析每一時刻的值, 並且將這一時刻和前面時刻的理解合併在一起, 生成當前時刻對前面數據的理解或記憶. 傳遞這種理解給下一時刻分析.

for epoch in range(EPOCH):
    for step, (b_x, b_y) in enumerate(train_loader):        
        b_x = b_x.view(-1, 28, 28)              # reshape x to (batch, time_step, input_size)

        output = rnn(b_x)                               # rnn output
        loss = loss_func(output, b_y)                   # cross entropy loss
        optimizer.zero_grad()                           # clear gradients for this training step
        loss.backward()                                 # backpropagation, compute gradients
        optimizer.step()                                # apply gradients

        if step % 50 == 0:
            test_output = rnn(test_x)                   # (samples, time_step, input_size)
            pred_y = torch.max(test_output, 1)[1].data.numpy()
            accuracy = float((pred_y == test_y).astype(int).sum()) / float(test_y.size)
            print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)

7.測試

我們將圖片數據看成一個時間上的連續數據, 每一行的像素點都是這個時刻的輸入, 讀完整張圖片就是從上而下的讀完了每行的像素點. 然後我們就可以拿出 RNN 在最後一步的分析值判斷圖片是哪一類了

test_output = rnn(test_x[:10].view(-1, 28, 28))
pred_y = torch.max(test_output, 1)[1].data.numpy()
print(pred_y, 'prediction number')
print(test_y[:10], 'real number')

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章