Pytorch學習筆記【12】:RNN(LSTM)實現手寫數字識別

注意看代碼註釋,解析全在註釋裏面了。

1. 代碼

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

# 定義一些參數
EPOCH = 1               # 訓練次數
BATCH_SIZE = 64         # 一次訓練的數據量,可以理解爲有多少條句子
TIME_STEP = 28          # 可以理解爲一個句子的序列長度
INPUT_SIZE = 28         # 可以理解爲每個詞向量的維度,也就是輸入維度,假如是3,那就是3
LR = 0.01               # learning rate
DOWNLOAD_MNIST = False   # set to True if haven't download the data


# 定義數據集
train_data = dsets.MNIST(
    root='./mnist/',
    train=True,                         # this is training data
    transform=transforms.ToTensor(),    # Converts a PIL.Image or numpy.ndarray to
                                        # torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
    download=DOWNLOAD_MNIST,            # download it if you don't have it
)

# plot one example
print(train_data.train_data.size())     # (60000, 28, 28)
print(train_data.train_labels.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)

# convert test data into Variable, pick 2000 samples to speed up testing
test_data = dsets.MNIST(root='./mnist/', train=False, transform=transforms.ToTensor())
test_x = test_data.test_data.type(torch.FloatTensor)[:2000]/255.   # shape (2000, 28, 28) value in range(0,1)
test_y = test_data.test_labels.numpy()[:2000]    # covert to numpy array


# 定義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=28,         # 隱藏層神經元節點個數
            num_layers=2,           # 神經元層數
            batch_first=True,       # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size)
        )

        self.out = nn.Linear(28, 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)   # h_n就是h狀態,h_c就是細胞的狀態

        # choose r_out at the last time step
        out = self.out(r_out[:, -1, :]) # 我們只要每一個time_step裏的最後的一個。比如64個矩陣,每個28*28,我們只要每一個的第28次的那個數據。
        return out


rnn = RNN()
print(rnn)

optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)   # optimize all cnn parameters
loss_func = nn.CrossEntropyLoss()                       # the target label is not one-hotted

# training and testing
for epoch in range(EPOCH):
    for step, (b_x, b_y) in enumerate(train_loader):        # gives batch data
        # print('before reshape x: ',b_x)
        b_x = b_x.view(-1, 28, 28)              # reshape x to (batch, time_step, input_size)
        # print('after reshape x: ',b_x)
        # print('result b_y: ',b_y)
        output = rnn(b_x)                               # rnn output
        # print(output)
        # print(torch.max(output, 1))
        # print(torch.max(output, 1)[1])
        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
        # test_output = rnn(test_x)  # (samples, time_step, input_size)
        # print('output: ',test_output)
        # print(torch.max(test_output, 1))
        # print(torch.max(test_output, 1)[1])
        # pred_y = torch.max(test_output, 1)[1].data.numpy()
        # print(pred_y)
        # print(test_y)
        # break
        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)

# print 10 predictions from test data
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')

2. 運行結果

發佈了234 篇原創文章 · 獲贊 71 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章