Skip to content

Commit fb2affb

Browse files
committed
update
1 parent 1e60b68 commit fb2affb

File tree

18 files changed

+191
-24
lines changed

18 files changed

+191
-24
lines changed

codes/GAE/task0_train.py

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
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()

codes/PPO/agent.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
66
Date: 2021-03-23 15:17:42
77
LastEditor: John
8-
LastEditTime: 2021-04-28 10:11:09
8+
LastEditTime: 2021-09-26 22:02:00
99
Discription:
1010
Environment:
1111
'''
@@ -41,10 +41,8 @@ def choose_action(self, observation):
4141

4242
def update(self):
4343
for _ in range(self.n_epochs):
44-
state_arr, action_arr, old_prob_arr, vals_arr,\
45-
reward_arr, dones_arr, batches = \
46-
self.memory.sample()
47-
values = vals_arr
44+
state_arr, action_arr, old_prob_arr, vals_arr,reward_arr, dones_arr, batches = self.memory.sample()
45+
values = vals_arr[:]
4846
### compute advantage ###
4947
advantage = np.zeros(len(reward_arr), dtype=np.float32)
5048
for t in range(len(reward_arr)-1):

codes/PPO/memory.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
66
Date: 2021-03-23 15:30:46
77
LastEditor: John
8-
LastEditTime: 2021-03-23 15:30:55
8+
LastEditTime: 2021-09-26 22:00:07
99
Discription:
1010
Environment:
1111
'''
@@ -24,14 +24,9 @@ def sample(self):
2424
indices = np.arange(len(self.states), dtype=np.int64)
2525
np.random.shuffle(indices)
2626
batches = [indices[i:i+self.batch_size] for i in batch_step]
27-
return np.array(self.states),\
28-
np.array(self.actions),\
29-
np.array(self.probs),\
30-
np.array(self.vals),\
31-
np.array(self.rewards),\
32-
np.array(self.dones),\
33-
batches
34-
27+
return np.array(self.states),np.array(self.actions),np.array(self.probs),\
28+
np.array(self.vals),np.array(self.rewards),np.array(self.dones),batches
29+
3530
def push(self, state, action, probs, vals, reward, done):
3631
self.states.append(state)
3732
self.actions.append(action)

codes/PPO/task0_train.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
66
Date: 2021-03-22 16:18:10
77
LastEditor: John
8-
LastEditTime: 2021-05-06 00:43:36
8+
LastEditTime: 2021-09-26 22:05:00
99
Discription:
1010
Environment:
1111
'''
@@ -17,6 +17,7 @@
1717
import gym
1818
import torch
1919
import datetime
20+
import tqdm
2021
from PPO.agent import PPO
2122
from common.plot import plot_rewards
2223
from common.utils import save_results,make_dir
@@ -51,7 +52,7 @@ def env_agent_config(cfg,seed=1):
5152
return env,agent
5253

5354
def train(cfg,env,agent):
54-
print('Start to train !')
55+
print('开始训练!')
5556
print(f'Env:{cfg.env}, Algorithm:{cfg.algo}, Device:{cfg.device}')
5657
rewards= []
5758
ma_rewards = [] # moving average rewards
@@ -75,7 +76,7 @@ def train(cfg,env,agent):
7576
0.9*ma_rewards[-1]+0.1*ep_reward)
7677
else:
7778
ma_rewards.append(ep_reward)
78-
print(f"Episode:{i_ep+1}/{cfg.train_eps}, Reward:{ep_reward:.3f}")
79+
print(f"回合:{i_ep+1}/{cfg.train_eps},奖励:{ep_reward:.2f}")
7980
print('Complete training!')
8081
return rewards,ma_rewards
8182

Binary file not shown.
Binary file not shown.
Binary file not shown.
48.7 KB
Loading
Binary file not shown.
Binary file not shown.

0 commit comments

Comments
 (0)