|
| 1 | +""" |
| 2 | +Example code of a simple RNN, GRU, LSTM on the MNIST dataset. |
| 3 | +
|
| 4 | +Programmed by Aladdin Persson <aladdin.persson at hotmail dot com> |
| 5 | +* 2020-05-09 Initial coding |
| 6 | +
|
| 7 | +""" |
| 8 | + |
| 9 | +# Imports |
| 10 | +import torch |
| 11 | +import torchvision # torch package for vision related things |
| 12 | +import torch.nn.functional as F # Parameterless functions, like (some) activation functions |
| 13 | +import torchvision.datasets as datasets # Standard datasets |
| 14 | +import torchvision.transforms as transforms # Transformations we can perform on our dataset for augmentation |
| 15 | +from torch import optim # For optimizers like SGD, Adam, etc. |
| 16 | +from torch import nn # All neural network modules |
| 17 | +from torch.utils.data import DataLoader # Gives easier dataset managment by creating mini batches etc. |
| 18 | +from tqdm import tqdm # For a nice progress bar! |
| 19 | + |
| 20 | +# Set device |
| 21 | +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 22 | + |
| 23 | +# Hyperparameters |
| 24 | +input_size = 28 |
| 25 | +hidden_size = 256 |
| 26 | +num_layers = 2 |
| 27 | +num_classes = 10 |
| 28 | +sequence_length = 28 |
| 29 | +learning_rate = 0.005 |
| 30 | +batch_size = 64 |
| 31 | +num_epochs = 3 |
| 32 | + |
| 33 | +# Recurrent neural network (many-to-one) |
| 34 | +class RNN(nn.Module): |
| 35 | + def __init__(self, input_size, hidden_size, num_layers, num_classes): |
| 36 | + super(RNN, self).__init__() |
| 37 | + self.hidden_size = hidden_size |
| 38 | + self.num_layers = num_layers |
| 39 | + self.rnn = nn.RNN(input_size, hidden_size, num_layers, batch_first=True) |
| 40 | + self.fc = nn.Linear(hidden_size * sequence_length, num_classes) |
| 41 | + |
| 42 | + def forward(self, x): |
| 43 | + # Set initial hidden and cell states |
| 44 | + h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) |
| 45 | + |
| 46 | + # Forward propagate LSTM |
| 47 | + out, _ = self.rnn(x, h0) |
| 48 | + out = out.reshape(out.shape[0], -1) |
| 49 | + |
| 50 | + # Decode the hidden state of the last time step |
| 51 | + out = self.fc(out) |
| 52 | + return out |
| 53 | + |
| 54 | + |
| 55 | +# Recurrent neural network with GRU (many-to-one) |
| 56 | +class RNN_GRU(nn.Module): |
| 57 | + def __init__(self, input_size, hidden_size, num_layers, num_classes): |
| 58 | + super(RNN_GRU, self).__init__() |
| 59 | + self.hidden_size = hidden_size |
| 60 | + self.num_layers = num_layers |
| 61 | + self.gru = nn.GRU(input_size, hidden_size, num_layers, batch_first=True) |
| 62 | + self.fc = nn.Linear(hidden_size * sequence_length, num_classes) |
| 63 | + |
| 64 | + def forward(self, x): |
| 65 | + # Set initial hidden and cell states |
| 66 | + h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) |
| 67 | + |
| 68 | + # Forward propagate LSTM |
| 69 | + out, _ = self.gru(x, h0) |
| 70 | + out = out.reshape(out.shape[0], -1) |
| 71 | + |
| 72 | + # Decode the hidden state of the last time step |
| 73 | + out = self.fc(out) |
| 74 | + return out |
| 75 | + |
| 76 | + |
| 77 | +# Recurrent neural network with LSTM (many-to-one) |
| 78 | +class RNN_LSTM(nn.Module): |
| 79 | + def __init__(self, input_size, hidden_size, num_layers, num_classes): |
| 80 | + super(RNN_LSTM, self).__init__() |
| 81 | + self.hidden_size = hidden_size |
| 82 | + self.num_layers = num_layers |
| 83 | + self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True) |
| 84 | + self.fc = nn.Linear(hidden_size * sequence_length, num_classes) |
| 85 | + |
| 86 | + def forward(self, x): |
| 87 | + # Set initial hidden and cell states |
| 88 | + h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) |
| 89 | + c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) |
| 90 | + |
| 91 | + # Forward propagate LSTM |
| 92 | + out, _ = self.lstm( |
| 93 | + x, (h0, c0) |
| 94 | + ) # out: tensor of shape (batch_size, seq_length, hidden_size) |
| 95 | + out = out.reshape(out.shape[0], -1) |
| 96 | + |
| 97 | + # Decode the hidden state of the last time step |
| 98 | + out = self.fc(out) |
| 99 | + return out |
| 100 | + |
| 101 | + |
| 102 | +# Load Data |
| 103 | +train_dataset = datasets.MNIST(root="dataset/", train=True, transform=transforms.ToTensor(), download=True) |
| 104 | +test_dataset = datasets.MNIST(root="dataset/", train=False, transform=transforms.ToTensor(), download=True) |
| 105 | +train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) |
| 106 | +test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True) |
| 107 | + |
| 108 | +# Initialize network (try out just using simple RNN, or GRU, and then compare with LSTM) |
| 109 | +model = RNN_LSTM(input_size, hidden_size, num_layers, num_classes).to(device) |
| 110 | + |
| 111 | +# Loss and optimizer |
| 112 | +criterion = nn.CrossEntropyLoss() |
| 113 | +optimizer = optim.Adam(model.parameters(), lr=learning_rate) |
| 114 | + |
| 115 | +# Train Network |
| 116 | +for epoch in range(num_epochs): |
| 117 | + for batch_idx, (data, targets) in enumerate(tqdm(train_loader)): |
| 118 | + # Get data to cuda if possible |
| 119 | + data = data.to(device=device).squeeze(1) |
| 120 | + targets = targets.to(device=device) |
| 121 | + |
| 122 | + # forward |
| 123 | + scores = model(data) |
| 124 | + loss = criterion(scores, targets) |
| 125 | + |
| 126 | + # backward |
| 127 | + optimizer.zero_grad() |
| 128 | + loss.backward() |
| 129 | + |
| 130 | + # gradient descent update step/adam step |
| 131 | + optimizer.step() |
| 132 | + |
| 133 | +# Check accuracy on training & test to see how good our model |
| 134 | +def check_accuracy(loader, model): |
| 135 | + num_correct = 0 |
| 136 | + num_samples = 0 |
| 137 | + |
| 138 | + # Set model to eval |
| 139 | + model.eval() |
| 140 | + |
| 141 | + with torch.no_grad(): |
| 142 | + for x, y in loader: |
| 143 | + x = x.to(device=device).squeeze(1) |
| 144 | + y = y.to(device=device) |
| 145 | + |
| 146 | + scores = model(x) |
| 147 | + _, predictions = scores.max(1) |
| 148 | + num_correct += (predictions == y).sum() |
| 149 | + num_samples += predictions.size(0) |
| 150 | + |
| 151 | + # Toggle model back to train |
| 152 | + model.train() |
| 153 | + return num_correct / num_samples |
| 154 | + |
| 155 | + |
| 156 | +print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:2f}") |
| 157 | +print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}") |
0 commit comments