|
| 1 | +import numpy as np |
| 2 | +import math |
| 3 | + |
| 4 | +import torch |
| 5 | +import torch.optim as optim |
| 6 | +import torch.nn as nn |
| 7 | + |
| 8 | +from irlwpython.FigurePrinter import FigurePrinter |
| 9 | + |
| 10 | + |
| 11 | +class QNetwork(nn.Module): |
| 12 | + def __init__(self, input_size, output_size): |
| 13 | + super(QNetwork, self).__init__() |
| 14 | + self.fc1 = nn.Linear(input_size, 64) |
| 15 | + self.relu1 = nn.ReLU() |
| 16 | + self.fc2 = nn.Linear(64, 32) |
| 17 | + self.relu2 = nn.ReLU() |
| 18 | + self.output_layer = nn.Linear(32, output_size) |
| 19 | + |
| 20 | + self.printer = FigurePrinter() |
| 21 | + |
| 22 | + def forward(self, state): |
| 23 | + x = self.fc1(state) |
| 24 | + x = self.relu1(x) |
| 25 | + x = self.fc2(x) |
| 26 | + x = self.relu2(x) |
| 27 | + q_values = self.output_layer(x) |
| 28 | + return q_values |
| 29 | + |
| 30 | + |
| 31 | +class MaxEntropyDeepRL: |
| 32 | + def __init__(self, target, state_dim, action_size, feature_matrix, one_feature, learning_rate=0.001, gamma=0.99): |
| 33 | + self.feature_matrix = feature_matrix |
| 34 | + self.one_feature = one_feature |
| 35 | + |
| 36 | + self.target = target |
| 37 | + |
| 38 | + self.q_network = QNetwork(state_dim, action_size) |
| 39 | + self.target_q_network = QNetwork(state_dim, action_size) |
| 40 | + self.target_q_network.load_state_dict(self.q_network.state_dict()) |
| 41 | + self.optimizer = optim.Adam(self.q_network.parameters(), lr=learning_rate) |
| 42 | + |
| 43 | + self.gamma = gamma |
| 44 | + |
| 45 | + self.printer = FigurePrinter() |
| 46 | + |
| 47 | + def select_action(self, state, epsilon): |
| 48 | + """ |
| 49 | + Selects an action based on the q values from the network with epsilon greedy. |
| 50 | + :param state: |
| 51 | + :param epsilon: |
| 52 | + :return: |
| 53 | + """ |
| 54 | + if np.random.rand() < epsilon: |
| 55 | + return np.random.choice(3) |
| 56 | + else: |
| 57 | + with torch.no_grad(): |
| 58 | + q_values = self.q_network(torch.FloatTensor(state)) |
| 59 | + return torch.argmax(q_values).item() |
| 60 | + |
| 61 | + def update_q_network(self, state, action, reward, next_state, done): |
| 62 | + """ |
| 63 | + Updates the q network based on the reward |
| 64 | + :param state: |
| 65 | + :param action: |
| 66 | + :param reward: |
| 67 | + :param next_state: |
| 68 | + :param done: |
| 69 | + :return: |
| 70 | + """ |
| 71 | + state = torch.FloatTensor(state) |
| 72 | + next_state = torch.FloatTensor(next_state) |
| 73 | + q_values = self.q_network(state) |
| 74 | + next_q_values = self.target_q_network(next_state) |
| 75 | + |
| 76 | + target = q_values.clone() |
| 77 | + if not done: |
| 78 | + target[action] = reward + self.gamma * torch.max(next_q_values).item() |
| 79 | + else: |
| 80 | + target[action] = reward |
| 81 | + |
| 82 | + loss = nn.MSELoss()(q_values, target.detach()) |
| 83 | + self.optimizer.zero_grad() |
| 84 | + loss.backward() |
| 85 | + self.optimizer.step() |
| 86 | + |
| 87 | + def update_target_network(self): |
| 88 | + """ |
| 89 | + Updates the target network. |
| 90 | + :return: |
| 91 | + """ |
| 92 | + self.target_q_network.load_state_dict(self.q_network.state_dict()) |
| 93 | + |
| 94 | + def train(self, n_states, episodes=30000, max_steps=200, |
| 95 | + epsilon_start=1.0, |
| 96 | + epsilon_decay=0.995, epsilon_min=0.01): |
| 97 | + """ |
| 98 | + Trains the network using the maximum entropy deep reinforcement algorithm. |
| 99 | + :param n_states: |
| 100 | + :param episodes: Count of training episodes |
| 101 | + :param max_steps: Max steps per episode |
| 102 | + :param epsilon_start: |
| 103 | + :param epsilon_decay: |
| 104 | + :param epsilon_min: |
| 105 | + :return: |
| 106 | + """ |
| 107 | + learner_feature_expectations = np.zeros(n_states) |
| 108 | + |
| 109 | + epsilon = epsilon_start |
| 110 | + episode_arr, scores = [], [] |
| 111 | + |
| 112 | + best_reward = -math.inf |
| 113 | + for episode in range(episodes): |
| 114 | + state, info = self.target.env_reset() |
| 115 | + total_reward = 0 |
| 116 | + |
| 117 | + for step in range(max_steps): |
| 118 | + action = self.select_action(state, epsilon) |
| 119 | + |
| 120 | + next_state, reward, done, _, _ = self.target.env_step(action) |
| 121 | + total_reward += reward |
| 122 | + |
| 123 | + self.update_q_network(state, action, reward, next_state, done) |
| 124 | + self.update_target_network() |
| 125 | + |
| 126 | + # State counting for densitiy |
| 127 | + state_idx = self.target.state_to_idx(state) |
| 128 | + learner_feature_expectations += self.feature_matrix[int(state_idx)] |
| 129 | + |
| 130 | + state = next_state |
| 131 | + if done: |
| 132 | + break |
| 133 | + |
| 134 | + # Keep track of best performing network |
| 135 | + if total_reward > best_reward: |
| 136 | + best_reward = total_reward |
| 137 | + torch.save(self.q_network.state_dict(), |
| 138 | + f"../results/maxentropydeep_{episode}_best_network_w_{total_reward}_RL.pth") |
| 139 | + |
| 140 | + if (episode + 1) % 10 == 0: |
| 141 | + # calculate density |
| 142 | + learner = learner_feature_expectations / episode |
| 143 | + learner_feature_expectations = np.zeros(n_states) |
| 144 | + |
| 145 | + scores.append(total_reward) |
| 146 | + episode_arr.append(episode) |
| 147 | + epsilon = max(epsilon * epsilon_decay, epsilon_min) |
| 148 | + print(f"Episode: {episode + 1}, Total Reward: {total_reward}, Epsilon: {epsilon}") |
| 149 | + |
| 150 | + if (episode + 1) % 1000 == 0: |
| 151 | + score_avg = np.mean(scores) |
| 152 | + print('{} episode average score is {:.2f}'.format(episode, score_avg)) |
| 153 | + self.printer.save_plot_as_png(episode_arr, scores, |
| 154 | + f"../learning_curves/maxent_{episodes}_{episode}_qnetwork_RL.png") |
| 155 | + self.printer.save_heatmap_as_png(learner.reshape((20, 20)), f"../heatmap/learner_{episode}_deep_RL.png") |
| 156 | + self.printer.save_heatmap_as_png(self.theta.reshape((20, 20)), |
| 157 | + f"../heatmap/theta_{episode}_deep_RL.png") |
| 158 | + |
| 159 | + torch.save(self.q_network.state_dict(), f"../results/maxent_{episodes}_{episode}_network_main.pth") |
| 160 | + |
| 161 | + if episode == episodes - 1: |
| 162 | + self.printer.save_plot_as_png(episode_arr, scores, |
| 163 | + f"../learning_curves/maxentdeep_{episodes}_qdeep_RL.png") |
| 164 | + |
| 165 | + torch.save(self.q_network.state_dict(), f"src/irlwpython/results/maxentdeep_{episodes}_q_network_RL.pth") |
| 166 | + |
| 167 | + def test(self, model_path, epsilon=0.01, repeats=100): |
| 168 | + """ |
| 169 | + Tests the previous trained model. |
| 170 | + :return: |
| 171 | + """ |
| 172 | + self.q_network.load_state_dict(torch.load(model_path)) |
| 173 | + episodes, scores = [], [] |
| 174 | + |
| 175 | + for episode in range(repeats): |
| 176 | + state, info = self.target.env_reset() |
| 177 | + score = 0 |
| 178 | + |
| 179 | + while True: |
| 180 | + self.target.env_render() |
| 181 | + action = self.select_action(state, epsilon) |
| 182 | + next_state, reward, done, _, _ = self.target.env_step(action) |
| 183 | + |
| 184 | + score += reward |
| 185 | + state = next_state |
| 186 | + |
| 187 | + if done: |
| 188 | + scores.append(score) |
| 189 | + episodes.append(episode) |
| 190 | + break |
| 191 | + |
| 192 | + if episode % 1 == 0: |
| 193 | + print('{} episode score is {:.2f}'.format(episode, score)) |
| 194 | + |
| 195 | + self.printer.save_plot_as_png(episodes, scores, |
| 196 | + "src/irlwpython/learning_curves" |
| 197 | + "/test_maxentropydeep_best_model_RL_results.png") |
0 commit comments