import torch
from torch import nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import os
# Hyper Parameters
EPOCH = 10
BATCH_SIZE = 64
INPUT_SIZE = 28
LR = 0.01
DOWNLOAD_MNIST = False
class RNNnet(nn.Module):
def __init__(self):
super(RNNnet, self).__init__()
self.rnn = nn.LSTM(
input_size=INPUT_SIZE,
hidden_size=64,
num_layers=1,
batch_first=True
)
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)
# choose r_out at the last time step
out = self.out(r_out[:, -1, :])
return out
if __name__ == '__main__':
# Mnist digits dataset
if not (os.path.exists('./mnist/')) or not os.listdir('./mnist/'):
DOWNLOAD_MNIST = True
# 加载训练数据
train_data = dsets.MNIST(
root='./mnist/',
train=True,
transform=transforms.ToTensor(),
download=DOWNLOAD_MNIST
)
# plot one example
print(train_data.data.size()) # (60000, 28, 28)
print(train_data.targets.size()) # (60000)
plt.imshow(train_data.data[0].numpy(), cmap='gray')
plt.title('%i' % train_data.targets[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]
rnn = RNNnet()
print(rnn)
optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)
loss_func = nn.CrossEntropyLoss()
# training and testing
for epoch in range(EPOCH):
for step, (b_x, b_y) in enumerate(train_loader)
b_x = b_x.view(-1, 28, 28)
output = rnn(b_x)
loss = loss_func(output, b_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if step % 50 == 0:
test_output = rnn(test_x)
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')
PyTorch:RNN网络训练MNIST数据集
最新推荐文章于 2022-06-13 13:18:26 发布