RNN在文本預(yù)測等方面有著諸多使用,也是重要的神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu),其結(jié)構(gòu)包括RNN,LSTM,GRU等。本文以分類這一任務(wù)為基礎(chǔ)分析RNN的簡單結(jié)構(gòu)
1. 引入包和設(shè)置超參數(shù)
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
# Hyper Parameters
EPOCH = 1 # train the training data n times, to save time, we just train 1 epoch
B_S = 64
TIME_STEP = 28 # rnn time step / image height
INPUT_SIZE = 28 # rnn input size / image width
LR = 0.01 # learning rate
DOWNLOAD_MNIST = True # set to True if haven't download the data
2. 準(zhǔn)備MNIST數(shù)據(jù)
# Mnist digital dataset
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()
# Data Loader for easy mini-batch return in training
train_loader = torch.utils.data.DataLoader(dataset=train_data, batch_size=B_S, 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
注:
- torchvision.datasets.MNIST(root, train, transform,download):root為MNIST數(shù)據(jù)所在路徑,train為設(shè)置該數(shù)據(jù)集為訓(xùn)練數(shù)據(jù)(True)或檢驗(yàn)數(shù)據(jù)(False),transform表示轉(zhuǎn)換數(shù)據(jù)至某種形式,download為設(shè)置是否下載該數(shù)據(jù)(若已下載則設(shè)置為False)
- torch.utils.data.DataLoader(dataset, batch_size, shuffle):裝載訓(xùn)練數(shù)據(jù),其中dataset用于指定所裝載數(shù)據(jù)集路徑
3. 構(gòu)建RNN網(wǎng)絡(luò)
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 represents zero initial hidden state
# choose r_out at the last time step
out = self.out(r_out[:, -1, :])
return out
rnn = RNN()
print(rnn)
注1:
- self.rnn=nn.LSTM(input_size,hidden_size,num_layers ):設(shè)定第一層級的RNN網(wǎng)絡(luò)為LSTM,其中input_size表示輸入數(shù)據(jù)的維度,hidden_size表示隱藏神經(jīng)元數(shù)量,num_layers表示LSTM網(wǎng)絡(luò)的層數(shù)
- self.out = nn.Linear(P1, P2):P1表示隱藏神經(jīng)元個數(shù),P2表示輸出類別數(shù)
- LSTM存在兩個輸出和輸入,表示預(yù)測內(nèi)容與狀態(tài)
注2:不同LSTM比較
單層三隱藏神經(jīng)元LSTM
三層六隱藏神經(jīng)元LSTM
4. 選擇優(yōu)化器與損失函數(shù)
optimizer = torch.optim.Adam(rnn.parameters(), lr=LR) # optimize all cnn parameters
loss_func = nn.CrossEntropyLoss() # the target label is not one-hotted
注:
- adam():最常用優(yōu)化器之一,為AdaGrad與動量算法的組合
- nn.CrossEntropyLoss() :判斷實(shí)際輸出與期望輸出的差異程度,多用于分類問題中判斷預(yù)測目標(biāo)概率分布與實(shí)際概率分布的差異
5. 訓(xùn)練和測試
# training and testing
for epoch in range(EPOCH):
for step, (b_x, b_y) in enumerate(train_loader): # gives batch data
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)
# 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')

