|
| 1 | +import pickle as pkl |
| 2 | +import random |
| 3 | +from collections import namedtuple, deque |
| 4 | + |
| 5 | +from matplotlib import pyplot as plt |
| 6 | +from sklearn.metrics import confusion_matrix |
| 7 | +from torch.nn import Module, Linear, ReLU, Sequential |
| 8 | +from torch.optim import Adam |
| 9 | +import torch |
| 10 | + |
| 11 | +# https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html |
| 12 | +Transition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward')) |
| 13 | + |
| 14 | +# https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html |
| 15 | +class ReplayMemory(object): |
| 16 | + |
| 17 | + def __init__(self, capacity): |
| 18 | + self.memory = deque([], maxlen=capacity) |
| 19 | + |
| 20 | + def push(self, *args): |
| 21 | + """Save a transition""" |
| 22 | + self.memory.append(Transition(*args)) |
| 23 | + |
| 24 | + def sample(self, batch_size): |
| 25 | + return random.sample(self.memory, batch_size) |
| 26 | + |
| 27 | + def __len__(self): |
| 28 | + return len(self.memory) |
| 29 | + |
| 30 | + |
| 31 | +class ANN(Module): |
| 32 | + def __init__(self, input_dim, output_dim): |
| 33 | + super(ANN, self).__init__() |
| 34 | + self.sequence = Sequential( |
| 35 | + Linear(input_dim, 1000), |
| 36 | + ReLU(), |
| 37 | + Linear(1000, 100), |
| 38 | + ReLU(), |
| 39 | + Linear(100, output_dim) |
| 40 | + ) |
| 41 | + |
| 42 | + def forward(self, x): |
| 43 | + x = x.to(torch.float32) |
| 44 | + return self.sequence(x) |
| 45 | + |
| 46 | + |
| 47 | +class DQN: |
| 48 | + def __init__(self, input_dim, output_dim, gamma=0.99, batch_size=128, device='cpu'): |
| 49 | + self.policy_net = ANN(input_dim, output_dim) |
| 50 | + self.target_net = ANN(input_dim, output_dim) |
| 51 | + self.optimizer = Adam(self.policy_net.parameters()) |
| 52 | + self.memory = ReplayMemory(10000) |
| 53 | + self.gamma = gamma |
| 54 | + self.batch_size = batch_size |
| 55 | + self.device = device |
| 56 | + |
| 57 | + def select_action(self, state, epsilon): |
| 58 | + # Random action |
| 59 | + if random.random() < epsilon: |
| 60 | + return torch.tensor([[random.randrange(2)]], dtype=torch.float32) |
| 61 | + |
| 62 | + # ANN action |
| 63 | + else: |
| 64 | + with torch.no_grad(): |
| 65 | + return self.policy_net(state).argmax() |
| 66 | + |
| 67 | + def optimize_model(self): |
| 68 | + if len(self.memory) < self.batch_size: |
| 69 | + return |
| 70 | + transitions = self.memory.sample(self.batch_size) |
| 71 | + batch = Transition(*zip(*transitions)) |
| 72 | + |
| 73 | + non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, |
| 74 | + batch.next_state)), device=self.device, dtype=torch.bool) |
| 75 | + non_final_next_states = torch.cat([s for s in batch.next_state |
| 76 | + if s is not None]).reshape(-1, 2) |
| 77 | + state_batch = torch.cat(batch.state).reshape(-1, 2) |
| 78 | + action_batch = torch.tensor(batch.action).to(torch.int64) |
| 79 | + reward_batch = torch.tensor(batch.reward) |
| 80 | + |
| 81 | + # Compute Q(s_t, a) |
| 82 | + state_action_values = self.policy_net(state_batch)[action_batch] |
| 83 | + |
| 84 | + # Compute V(s_{t+1}) for all next states. |
| 85 | + next_state_values = torch.zeros(self.batch_size, device=self.device) |
| 86 | + with torch.no_grad(): |
| 87 | + next_state_values[non_final_mask] = self.target_net(non_final_next_states).max(1).values |
| 88 | + |
| 89 | + # Compute the expected Q values |
| 90 | + expected_state_action_values = (next_state_values * self.gamma) + reward_batch |
| 91 | + |
| 92 | + # Compute Loss |
| 93 | + criterion = torch.nn.SmoothL1Loss() |
| 94 | + loss = criterion(state_action_values, expected_state_action_values.unsqueeze(1)) |
| 95 | + |
| 96 | + # Optimize the model |
| 97 | + self.optimizer.zero_grad() |
| 98 | + loss.backward() |
| 99 | + # In-place gradient clipping |
| 100 | + torch.nn.utils.clip_grad_value_(self.policy_net.parameters(), 100) |
| 101 | + self.optimizer.step() |
| 102 | + |
| 103 | + def update_target(self, tau=0.005): |
| 104 | + target_net_state_dict = self.target_net.state_dict() |
| 105 | + policy_net_state_dict = self.policy_net.state_dict() |
| 106 | + for key in policy_net_state_dict: |
| 107 | + target_net_state_dict[key] = policy_net_state_dict[key]*tau + target_net_state_dict[key] * (1 - tau) |
| 108 | + |
| 109 | + |
| 110 | +class Mem_Dataset(torch.utils.data.Dataset): |
| 111 | + def __init__(self, samples, labels): |
| 112 | + self.samples = samples |
| 113 | + self.labels = labels |
| 114 | + |
| 115 | + def __len__(self): |
| 116 | + return len(self.samples) |
| 117 | + |
| 118 | + def __getitem__(self, idx): |
| 119 | + # Compress spike train into windows for dimension reduction |
| 120 | + return self.samples[idx].sum(0).squeeze(), self.labels[idx] |
| 121 | + |
| 122 | + |
| 123 | +if __name__ == '__main__': |
| 124 | + ### ANN for input spike trains ### |
| 125 | + # Load recalled memory samples ## |
| 126 | + with open('Data/grid_cell_spk_trains.pkl', 'rb') as f: |
| 127 | + samples, labels = pkl.load(f) |
| 128 | + |
| 129 | + ## Initialize ANN ## |
| 130 | + in_dim = samples[0].shape[1] |
| 131 | + model = ANN(in_dim, 2) |
| 132 | + optimizer = Adam(model.parameters()) |
| 133 | + criterion = torch.nn.MSELoss() |
| 134 | + dataset = Mem_Dataset(samples, labels) |
| 135 | + train_size = int(0.8 * len(dataset)) |
| 136 | + test_size = len(dataset) - train_size |
| 137 | + train_set, test_set = torch.utils.data.random_split(dataset, [train_size, test_size]) |
| 138 | + train_loader = torch.utils.data.DataLoader(train_set, batch_size=32, shuffle=True) |
| 139 | + test_loader = torch.utils.data.DataLoader(test_set, batch_size=32, shuffle=True) |
| 140 | + |
| 141 | + ## Training ## |
| 142 | + loss_log = [] |
| 143 | + accuracy_log = [] |
| 144 | + for epoch in range(10): |
| 145 | + total_loss = 0 |
| 146 | + correct = 0 |
| 147 | + for memory_batch, positions in train_loader: |
| 148 | + # positions_ = torch.tensor([[positions_[0][i], positions_[1][i]] for i, _ in enumerate(positions_[0])], dtype=torch.float32) |
| 149 | + optimizer.zero_grad() |
| 150 | + outputs = model(memory_batch) |
| 151 | + loss = criterion(outputs, positions.to(torch.float32)) |
| 152 | + loss.backward() |
| 153 | + optimizer.step() |
| 154 | + total_loss += loss.item() |
| 155 | + correct += torch.all(outputs.round() == positions.round(), |
| 156 | + dim=1).sum().item() |
| 157 | + accuracy_log.append(correct / len(train_set)) |
| 158 | + loss_log.append(total_loss) |
| 159 | + |
| 160 | + plt.xlabel('Epoch') |
| 161 | + plt.ylabel('Loss') |
| 162 | + plt.title('Training Loss') |
| 163 | + plt.plot(loss_log) |
| 164 | + plt.show() |
| 165 | + plt.xlabel('Epoch') |
| 166 | + plt.ylabel('Accuracy') |
| 167 | + plt.title('Training Accuracy') |
| 168 | + plt.plot(accuracy_log) |
| 169 | + plt.show() |
| 170 | + |
| 171 | + ## Testing ## |
| 172 | + total = 0 |
| 173 | + correct = 0 |
| 174 | + confusion_matrix = torch.zeros(25, 25) |
| 175 | + out_of_bounds = 0 |
| 176 | + with torch.no_grad(): |
| 177 | + for memories, labels in test_loader: |
| 178 | + outputs = model(memories) |
| 179 | + loss = criterion(outputs, labels) |
| 180 | + total += len(labels) |
| 181 | + correct += torch.all(outputs.round() == labels.round(), |
| 182 | + dim=1).sum().item() # Check if prediction for both x and y are correct |
| 183 | + for t, p in zip(labels, outputs): |
| 184 | + label_ind = int(t[0].round() * 5 + t[1].round()) |
| 185 | + pred_ind = int(p[0].round() * 5 + p[1].round()) |
| 186 | + if label_ind < 0 or label_ind >= 25 or pred_ind < 0 or pred_ind >= 25: |
| 187 | + out_of_bounds += 1 |
| 188 | + else: |
| 189 | + confusion_matrix[label_ind, pred_ind] += 1 |
| 190 | + |
| 191 | + plt.imshow(confusion_matrix) |
| 192 | + plt.title('Confusion Matrix') |
| 193 | + plt.xlabel('Predicted') |
| 194 | + plt.ylabel('True Label') |
| 195 | + plt.colorbar() |
| 196 | + plt.show() |
| 197 | + |
| 198 | + print(f'Accuracy: {round(correct / total, 3)*100}%') |
| 199 | + |
0 commit comments