MNIST手写数据
import torch
from torch import nn
import torchvision.datasets as Data
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
torch.manual_seed(1)
EPOCH = 1
BATCH_SIZE = 64
TIME_STEP = 28 #rnn时间补数/图片宽度
INPUT_SIZE = 28 #rnn每步输入值/图片每行像素
LR = 0.01
DOWNLOAD_MNIST = True
train_data = torchvision.datasets.MNIST(
root='./mnist',
train=True,
transform=torchvision.transforms.ToTensor(),
download=DOWNLOAD_MNIST,
)
同样,我们除了训练数据,还给一些测试数据,测试看看它有没有训练好。
test_data = torchvision.datasets.MNIST(
root='./mnist',
train=False,
)
train_loader = Data.DataLoader(dataset=train_data, shuffle=True, batch_size=BATCH_SIZE)
test_x = torch.unsqueeze(test_data.test_data, dim=1).type(torch.FloatTensor)[:2000]/255.
test_y = test_data.test_labels[:2000]
函数剖析:
pytorch学习 中 torch.squeeze() 和torch.unsqueeze()的用法
RNN模型
我们用一个class来建立RNN,这个RNN整体流程是
- (input0, state0) -> LSTM -> (output0, state1);
- (input1, state1) -> LSTM -> (output1, state2);
- …
- (inputN, stateN)-> LSTM -> (outputN, stateN+1);
- output -> Linear -> prediction.通过LSTM分析每一时刻的值,并且将这一时刻和前面时刻的理解合并在一起,生成当前时刻对前面数据的理解或记忆。传递这种理解给下一个时刻分析。
class RNN(nn.Module):
def __init__(self):
super(RNN,self).__init__()
self.rnn = nn.LSTM(
input_size=28,
hidden_size=64,
num_layers=1,
batch_size=True, # input & output 会是以 batch size 为第一维度的特征集 e.g. (batch, time_step, input_size)
)
self.output = 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) LSTM 有两个 hidden states, h_n 是分线, h_c 是主线
# h_c shape (n_layers, batch, hidden_size)
r_out, (h_n, h_c) = rnn(x)
out = self.output(r_out[:,-1,:])
return out
rnn = RNN()
print(rnn)
结果:
"""
RNN (
(rnn): LSTM(28, 64, batch_first=True)
(out): Linear (64 -> 10)
)
"""
函数剖析:
class torch.nn.RNN(* args, ** kwargs)
将一个多层的Elman RNN,激活函数为tanh或者ReLU,由于输入序列。
对于序列中每个元素,RNN每层的计算公式为
h
t
=
t
a
n
h
(
w
i
h
x
t
+
b
i
h
+
w
h
h
h
t
−
1
+
b
h
h
)
ht=tanh(w{ih} xt+b{ih}+w_{hh} h{t-1}+b{hh})
ht=tanh(wihxt+bih+whhht−1+bhh)
h
t
h_t
ht是时刻
t
t
t的隐状态,或者是第一层在时刻
t
t
t的输入。如果nonlinearity=‘relu’,那么将使用relu代替tanh作为激活函数。
参数说明:
# input_size - 输入x的特征数量。
# hidden_size - 隐层的特征数量。
# num_layers - RNN的层数。
# nonlinearity - 指定非线性函数使用tanh还是relu。默认是tanh
# bias - 如果是False, 那么RNN层就不会使用偏置权重
b
i
n
h
b_inh
binh和
b
h
h
b_hh
bhh,默认是True
#batch_first - 如果True的话,那么输入Tensor的shape应该是[batch_size, time_step, feature],输出也是这样。
# dropout - 如果值非零,那么除了最后一层外,其他层的输出都会套上一个dropout层。
# bidirectional - 如果True,将会变成一个双向RNN,默认为False。
RNN的输入:(input, h_0)
#input(seq_len, batch, input_size): 保存输入序列特征的tensor。input可以是被填充的变长的序列。细节请看torch.nn.utils.rnn.pack_padded_sequence()
# h_0 (num_layers * num_directions, batch, hidden_size): 保存着初始隐状态的tensor
RNN的输出: (output, h_n)
# output (seq_len, batch, hidden_size * num_directions): 保存着RNN最后一层的输出特征。如果输入是被填充过的序列,那么输出也是被填充的序列。
# h_n (num_layers * num_directions, batch, hidden_size): 保存着最后一个时刻的隐状态。
RNN模型参数:
# weight_ih_l[k] - 第k层的 input-hidden 权重, 可学习,形状是(input_size x hidden_size)。
# weight_hh_l[k] - 第k层的 hidden-hidden 权重, 可学习,形状是(hidden_size x hidden_size)
# bias_ih_l[k] - 第k层的 input-hidden 偏置, 可学习,形状是(hidden_size)
# bias_hh_l[k] - 第k层的 hidden-hidden 偏置, 可学习,形状是(hidden_size)
实例:
rnn = nn.RNN(10, 20, 2)
input = Variable(torch.randn(5, 3, 10))
h0 = Variable(torch.randn(2, 3, 20))
output, hn = rnn(input, h0)
训练
我们将图片数据看成一个时间上的连续数据,每一行的像素点都是这个时刻的输入,读完整张图片就是从上而下的读完了每行的像素点。然后我们就可以拿出RNN在最后一步的分析值判断图片是哪一类了。下面的代码省略了计算accuracy的部分。
optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)
loss_func = nn.CrossEntryLoss()
for epoch in range(EPOCH):
for step, (b_x, b_y) in enumerate(train_loader):
b_x = x.view(-1, 28, 28)
output = rnn(b_x)
loss = loss_func(output, b_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
"""
...
Epoch: 0 | train loss: 0.0945 | test accuracy: 0.94
Epoch: 0 | train loss: 0.0984 | test accuracy: 0.94
Epoch: 0 | train loss: 0.0332 | test accuracy: 0.95
Epoch: 0 | train loss: 0.1868 | test accuracy: 0.96
"""
最后我们再来取10个数据,看看预测的值到底对不对:
test_output = rnn(test_x[:10].view(-1, 28, 28))
pred_y = torch.max(test_output)[test_output, 1][1].data.numpy().squeeze()
print(pred_y, 'prediction number')
print(test_y[:10],'real number')
结果:
"""
[7 2 1 0 4 1 4 9 5 9] prediction number
[7 2 1 0 4 1 4 9 5 9] real number
"""
完整代码:
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
BATCH_SIZE = 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
# 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=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
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)
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
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')