|
| 1 | +import math |
| 2 | +import random |
| 3 | + |
| 4 | +import gym |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +import torch |
| 8 | +import torch.nn as nn |
| 9 | +import torch.optim as optim |
| 10 | +import torch.nn.functional as F |
| 11 | +from torch.distributions import Normal |
| 12 | +import matplotlib.pyplot as plt |
| 13 | +import seaborn as sns |
| 14 | +import sys,os |
| 15 | +curr_path = os.path.dirname(os.path.abspath(__file__)) # 当前文件所在绝对路径 |
| 16 | +parent_path = os.path.dirname(curr_path) # 父路径 |
| 17 | +sys.path.append(parent_path) # 添加父路径到系统路径sys.path |
| 18 | + |
| 19 | +use_cuda = torch.cuda.is_available() |
| 20 | +device = torch.device("cuda" if use_cuda else "cpu") |
| 21 | + |
| 22 | +from common.multiprocessing_env import SubprocVecEnv |
| 23 | + |
| 24 | +num_envs = 16 |
| 25 | +env_name = "Pendulum-v0" |
| 26 | + |
| 27 | +def make_env(): |
| 28 | + def _thunk(): |
| 29 | + env = gym.make(env_name) |
| 30 | + return env |
| 31 | + |
| 32 | + return _thunk |
| 33 | + |
| 34 | +envs = [make_env() for i in range(num_envs)] |
| 35 | +envs = SubprocVecEnv(envs) |
| 36 | + |
| 37 | +env = gym.make(env_name) |
| 38 | + |
| 39 | +def init_weights(m): |
| 40 | + if isinstance(m, nn.Linear): |
| 41 | + nn.init.normal_(m.weight, mean=0., std=0.1) |
| 42 | + nn.init.constant_(m.bias, 0.1) |
| 43 | + |
| 44 | +class ActorCritic(nn.Module): |
| 45 | + def __init__(self, num_inputs, num_outputs, hidden_size, std=0.0): |
| 46 | + super(ActorCritic, self).__init__() |
| 47 | + |
| 48 | + self.critic = nn.Sequential( |
| 49 | + nn.Linear(num_inputs, hidden_size), |
| 50 | + nn.ReLU(), |
| 51 | + nn.Linear(hidden_size, 1) |
| 52 | + ) |
| 53 | + |
| 54 | + self.actor = nn.Sequential( |
| 55 | + nn.Linear(num_inputs, hidden_size), |
| 56 | + nn.ReLU(), |
| 57 | + nn.Linear(hidden_size, num_outputs), |
| 58 | + ) |
| 59 | + self.log_std = nn.Parameter(torch.ones(1, num_outputs) * std) |
| 60 | + |
| 61 | + self.apply(init_weights) |
| 62 | + |
| 63 | + def forward(self, x): |
| 64 | + value = self.critic(x) |
| 65 | + mu = self.actor(x) |
| 66 | + std = self.log_std.exp().expand_as(mu) |
| 67 | + dist = Normal(mu, std) |
| 68 | + return dist, value |
| 69 | + |
| 70 | + |
| 71 | +def plot(frame_idx, rewards): |
| 72 | + plt.figure(figsize=(20,5)) |
| 73 | + plt.subplot(131) |
| 74 | + plt.title('frame %s. reward: %s' % (frame_idx, rewards[-1])) |
| 75 | + plt.plot(rewards) |
| 76 | + plt.show() |
| 77 | + |
| 78 | +def test_env(vis=False): |
| 79 | + state = env.reset() |
| 80 | + if vis: env.render() |
| 81 | + done = False |
| 82 | + total_reward = 0 |
| 83 | + while not done: |
| 84 | + state = torch.FloatTensor(state).unsqueeze(0).to(device) |
| 85 | + dist, _ = model(state) |
| 86 | + next_state, reward, done, _ = env.step(dist.sample().cpu().numpy()[0]) |
| 87 | + state = next_state |
| 88 | + if vis: env.render() |
| 89 | + total_reward += reward |
| 90 | + return total_reward |
| 91 | + |
| 92 | +def compute_gae(next_value, rewards, masks, values, gamma=0.99, tau=0.95): |
| 93 | + values = values + [next_value] |
| 94 | + gae = 0 |
| 95 | + returns = [] |
| 96 | + for step in reversed(range(len(rewards))): |
| 97 | + delta = rewards[step] + gamma * values[step + 1] * masks[step] - values[step] |
| 98 | + gae = delta + gamma * tau * masks[step] * gae |
| 99 | + returns.insert(0, gae + values[step]) |
| 100 | + return returns |
| 101 | + |
| 102 | +num_inputs = envs.observation_space.shape[0] |
| 103 | +num_outputs = envs.action_space.shape[0] |
| 104 | + |
| 105 | +#Hyper params: |
| 106 | +hidden_size = 256 |
| 107 | +lr = 3e-2 |
| 108 | +num_steps = 20 |
| 109 | + |
| 110 | +model = ActorCritic(num_inputs, num_outputs, hidden_size).to(device) |
| 111 | +optimizer = optim.Adam(model.parameters()) |
| 112 | + |
| 113 | +max_frames = 100000 |
| 114 | +frame_idx = 0 |
| 115 | +test_rewards = [] |
| 116 | + |
| 117 | +state = envs.reset() |
| 118 | + |
| 119 | +while frame_idx < max_frames: |
| 120 | + |
| 121 | + log_probs = [] |
| 122 | + values = [] |
| 123 | + rewards = [] |
| 124 | + masks = [] |
| 125 | + entropy = 0 |
| 126 | + |
| 127 | + for _ in range(num_steps): |
| 128 | + state = torch.FloatTensor(state).to(device) |
| 129 | + dist, value = model(state) |
| 130 | + |
| 131 | + action = dist.sample() |
| 132 | + next_state, reward, done, _ = envs.step(action.cpu().numpy()) |
| 133 | + |
| 134 | + log_prob = dist.log_prob(action) |
| 135 | + entropy += dist.entropy().mean() |
| 136 | + |
| 137 | + log_probs.append(log_prob) |
| 138 | + values.append(value) |
| 139 | + rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) |
| 140 | + masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) |
| 141 | + |
| 142 | + state = next_state |
| 143 | + frame_idx += 1 |
| 144 | + |
| 145 | + if frame_idx % 1000 == 0: |
| 146 | + test_rewards.append(np.mean([test_env() for _ in range(10)])) |
| 147 | + print(test_rewards[-1]) |
| 148 | + # plot(frame_idx, test_rewards) |
| 149 | + |
| 150 | + next_state = torch.FloatTensor(next_state).to(device) |
| 151 | + _, next_value = model(next_state) |
| 152 | + returns = compute_gae(next_value, rewards, masks, values) |
| 153 | + |
| 154 | + log_probs = torch.cat(log_probs) |
| 155 | + returns = torch.cat(returns).detach() |
| 156 | + values = torch.cat(values) |
| 157 | + |
| 158 | + advantage = returns - values |
| 159 | + |
| 160 | + actor_loss = -(log_probs * advantage.detach()).mean() |
| 161 | + critic_loss = advantage.pow(2).mean() |
| 162 | + |
| 163 | + loss = actor_loss + 0.5 * critic_loss - 0.001 * entropy |
| 164 | + |
| 165 | + optimizer.zero_grad() |
| 166 | + loss.backward() |
| 167 | + optimizer.step() |
0 commit comments