1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
| import gym import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import time
GAMMA = 0.95 LR = 0.01
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") torch.backends.cudnn.enabled = False
class PGNetwork(nn.Module): def __init__(self, state_dim, action_dim): super(PGNetwork, self).__init__() self.fc1 = nn.Linear(state_dim, 20) self.fc2 = nn.Linear(20, action_dim)
def forward(self, x): out = F.relu(self.fc1(x)) out = self.fc2(out) return out
def initialize_weights(self): for m in self.modules(): nn.init.normal_(m.weight.data, 0, 0.1) nn.init.constant_(m.bias.data, 0.01)
class Actor(object): def __init__(self, env): self.state_dim = env.observation_space.shape[0] self.action_dim = env.action_space.n
self.network = PGNetwork(state_dim=self.state_dim, action_dim=self.action_dim).to(device) self.optimizer = torch.optim.Adam(self.network.parameters(), lr=LR)
self.time_step = 0
def choose_action(self, observation): observation = torch.FloatTensor(observation).to(device) network_output = self.network.forward(observation) with torch.no_grad(): prob_weights = F.softmax(network_output, dim=0).cuda().data.cpu().numpy() action = np.random.choice(range(prob_weights.shape[0]), p=prob_weights) return action
def learn(self, state, action, td_error): self.time_step += 1 softmax_input = self.network.forward(torch.FloatTensor(state).to(device)).unsqueeze(0) action = torch.LongTensor([action]).to(device) neg_log_prob = F.cross_entropy(input=softmax_input, target=action, reduction='none')
loss_a = -neg_log_prob * td_error self.optimizer.zero_grad() loss_a.backward() self.optimizer.step()
EPSILON = 0.01 REPLAY_SIZE = 10000 BATCH_SIZE = 32 REPLACE_TARGET_FREQ = 10
class QNetwork(nn.Module): def __init__(self, state_dim, action_dim): super(QNetwork, self).__init__() self.fc1 = nn.Linear(state_dim, 20) self.fc2 = nn.Linear(20, 1)
def forward(self, x): out = F.relu(self.fc1(x)) out = self.fc2(out) return out
def initialize_weights(self): for m in self.modules(): nn.init.normal_(m.weight.data, 0, 0.1) nn.init.constant_(m.bias.data, 0.01)
class Critic(object): def __init__(self, env): self.state_dim = env.observation_space.shape[0] self.action_dim = env.action_space.n
self.network = QNetwork(state_dim=self.state_dim, action_dim=self.action_dim).to(device) self.optimizer = torch.optim.Adam(self.network.parameters(), lr=LR) self.loss_func = nn.MSELoss()
self.time_step = 0 self.epsilon = EPSILON
def train_Q_network(self, state, reward, next_state): s, s_ = torch.FloatTensor(state).to(device), torch.FloatTensor(next_state).to(device) v = self.network.forward(s) v_ = self.network.forward(s_)
loss_q = self.loss_func(reward + GAMMA * v_, v) self.optimizer.zero_grad() loss_q.backward() self.optimizer.step()
with torch.no_grad(): td_error = reward + GAMMA * v_ - v
return td_error
ENV_NAME = 'CartPole-v0' EPISODE = 3000 STEP = 3000 TEST = 10
def main(): env = gym.make(ENV_NAME) actor = Actor(env) critic = Critic(env)
for episode in range(EPISODE): state = env.reset() for step in range(STEP): action = actor.choose_action(state) next_state, reward, done, _ = env.step(action) td_error = critic.train_Q_network(state, reward, next_state) actor.learn(state, action, td_error) state = next_state if done: break
if episode % 100 == 0: total_reward = 0 for i in range(TEST): state = env.reset() for j in range(STEP): env.render() action = actor.choose_action(state) state, reward, done, _ = env.step(action) total_reward += reward if done: break ave_reward = total_reward/TEST print('episode: ', episode, 'Evaluation Average Reward:', ave_reward)
if __name__ == '__main__': time_start = time.time() main() time_end = time.time() print('Total time is ', time_end - time_start, 's')
|