update
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
## A2C
|
||||
|
||||
|
||||
|
||||
https://towardsdatascience.com/understanding-actor-critic-methods-931b97b6df3f
|
||||
@@ -1,32 +1,27 @@
|
||||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
'''
|
||||
Author: John
|
||||
Author: JiangJi
|
||||
Email: johnjim0816@gmail.com
|
||||
Date: 2020-11-03 20:47:09
|
||||
LastEditor: John
|
||||
LastEditTime: 2021-03-20 17:41:21
|
||||
Date: 2021-05-03 22:16:08
|
||||
LastEditor: JiangJi
|
||||
LastEditTime: 2021-05-03 22:23:48
|
||||
Discription:
|
||||
Environment:
|
||||
'''
|
||||
from A2C.model import ActorCritic
|
||||
import torch.optim as optim
|
||||
|
||||
from A2C.model import ActorCritic
|
||||
class A2C:
|
||||
def __init__(self,state_dim, action_dim, cfg):
|
||||
self.gamma = 0.99
|
||||
self.model = ActorCritic(state_dim, action_dim, hidden_dim=cfg.hidden_dim).to(cfg.device)
|
||||
self.optimizer = optim.Adam(self.model.parameters(),lr=cfg.lr)
|
||||
def choose_action(self, state):
|
||||
dist, value = self.model(state)
|
||||
action = dist.sample()
|
||||
return action
|
||||
def __init__(self,state_dim,action_dim,cfg) -> None:
|
||||
self.gamma = cfg.gamma
|
||||
self.device = cfg.device
|
||||
self.model = ActorCritic(state_dim, action_dim, cfg.hidden_size).to(self.device)
|
||||
self.optimizer = optim.Adam(self.model.parameters())
|
||||
|
||||
def compute_returns(self,next_value, rewards, masks):
|
||||
R = next_value
|
||||
returns = []
|
||||
for step in reversed(range(len(rewards))):
|
||||
R = rewards[step] + self.gamma * R * masks[step]
|
||||
returns.insert(0, R)
|
||||
return returns
|
||||
def update(self):
|
||||
pass
|
||||
return returns
|
||||
@@ -1,48 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
'''
|
||||
Author: John
|
||||
Email: johnjim0816@gmail.com
|
||||
Date: 2020-10-30 15:39:37
|
||||
LastEditor: John
|
||||
LastEditTime: 2021-03-17 20:19:14
|
||||
Discription:
|
||||
Environment:
|
||||
'''
|
||||
|
||||
import gym
|
||||
from A2C.multiprocessing_env import SubprocVecEnv
|
||||
|
||||
# num_envs = 16
|
||||
# env = "Pendulum-v0"
|
||||
|
||||
def make_envs(num_envs=16,env="Pendulum-v0"):
|
||||
''' 创建多个子环境
|
||||
'''
|
||||
num_envs = 16
|
||||
env = "CartPole-v0"
|
||||
def make_env():
|
||||
def _thunk():
|
||||
env = gym.make(env)
|
||||
return env
|
||||
|
||||
return _thunk
|
||||
|
||||
envs = [make_env() for i in range(num_envs)]
|
||||
envs = SubprocVecEnv(envs)
|
||||
return envs
|
||||
# if __name__ == "__main__":
|
||||
|
||||
# num_envs = 16
|
||||
# env = "CartPole-v0"
|
||||
# def make_env():
|
||||
# def _thunk():
|
||||
# env = gym.make(env)
|
||||
# return env
|
||||
|
||||
# return _thunk
|
||||
|
||||
# envs = [make_env() for i in range(num_envs)]
|
||||
# envs = SubprocVecEnv(envs)
|
||||
if __name__ == "__main__":
|
||||
envs = make_envs(num_envs=16,env="CartPole-v0")
|
||||
@@ -1,106 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
'''
|
||||
@Author: John
|
||||
@Email: johnjim0816@gmail.com
|
||||
@Date: 2020-06-11 20:58:21
|
||||
@LastEditor: John
|
||||
LastEditTime: 2021-04-05 11:14:39
|
||||
@Discription:
|
||||
@Environment: python 3.7.9
|
||||
'''
|
||||
import sys,os
|
||||
curr_path = os.path.dirname(__file__)
|
||||
parent_path=os.path.dirname(curr_path)
|
||||
sys.path.append(parent_path) # add current terminal path to sys.path
|
||||
|
||||
import torch
|
||||
import gym
|
||||
import datetime
|
||||
from A2C.agent import A2C
|
||||
from common.utils import save_results,make_dir,del_empty_dir
|
||||
|
||||
|
||||
|
||||
SEQUENCE = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") # 获取当前时间
|
||||
SAVED_MODEL_PATH = os.path.split(os.path.abspath(__file__))[0]+"/saved_model/"+SEQUENCE+'/' # 生成保存的模型路径
|
||||
if not os.path.exists(os.path.split(os.path.abspath(__file__))[0]+"/saved_model/"):
|
||||
os.mkdir(os.path.split(os.path.abspath(__file__))[0]+"/saved_model/")
|
||||
if not os.path.exists(SAVED_MODEL_PATH):
|
||||
os.mkdir(SAVED_MODEL_PATH)
|
||||
RESULT_PATH = os.path.split(os.path.abspath(__file__))[0]+"/results/"+SEQUENCE+'/' # 存储reward的路径
|
||||
if not os.path.exists(os.path.split(os.path.abspath(__file__))[0]+"/results/"):
|
||||
os.mkdir(os.path.split(os.path.abspath(__file__))[0]+"/results/")
|
||||
if not os.path.exists(RESULT_PATH):
|
||||
os.mkdir(RESULT_PATH)
|
||||
|
||||
class A2CConfig:
|
||||
def __init__(self):
|
||||
self.gamma = 0.99
|
||||
self.lr = 3e-4 # learnning rate
|
||||
self.actor_lr = 1e-4 # learnning rate of actor network
|
||||
self.memory_capacity = 10000 # capacity of replay memory
|
||||
self.batch_size = 128
|
||||
self.train_eps = 200
|
||||
self.train_steps = 200
|
||||
self.eval_eps = 200
|
||||
self.eval_steps = 200
|
||||
self.target_update = 4
|
||||
self.hidden_dim=256
|
||||
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
def train(cfg,env,agent):
|
||||
print('Start to train ! ')
|
||||
for i_episode in range(cfg.train_eps):
|
||||
state = env.reset()
|
||||
log_probs = []
|
||||
values = []
|
||||
rewards = []
|
||||
masks = []
|
||||
entropy = 0
|
||||
ep_reward = 0
|
||||
for i_step in range(cfg.train_steps):
|
||||
state = torch.FloatTensor(state).to(cfg.device)
|
||||
dist, value = agent.model(state)
|
||||
action = dist.sample()
|
||||
next_state, reward, done, _ = env.step(action.cpu().numpy())
|
||||
ep_reward+=reward
|
||||
state = next_state
|
||||
log_prob = dist.log_prob(action)
|
||||
entropy += dist.entropy().mean()
|
||||
log_probs.append(log_prob)
|
||||
values.append(value)
|
||||
rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(cfg.device))
|
||||
masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(cfg.device))
|
||||
if done:
|
||||
break
|
||||
print('Episode:{}/{}, Reward:{}, Steps:{}, Done:{}'.format(i_episode+1,cfg.train_eps,ep_reward,i_step+1,done))
|
||||
next_state = torch.FloatTensor(next_state).to(cfg.device)
|
||||
_, next_value =agent.model(next_state)
|
||||
returns = agent.compute_returns(next_value, rewards, masks)
|
||||
|
||||
log_probs = torch.cat(log_probs)
|
||||
returns = torch.cat(returns).detach()
|
||||
values = torch.cat(values)
|
||||
advantage = returns - values
|
||||
actor_loss = -(log_probs * advantage.detach()).mean()
|
||||
critic_loss = advantage.pow(2).mean()
|
||||
loss = actor_loss + 0.5 * critic_loss - 0.001 * entropy
|
||||
|
||||
agent.optimizer.zero_grad()
|
||||
loss.backward()
|
||||
agent.optimizer.step()
|
||||
|
||||
print('Complete training!')
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cfg = A2CConfig()
|
||||
env = gym.make('CartPole-v0')
|
||||
env.seed(1) # set random seed for env
|
||||
state_dim = env.observation_space.shape[0]
|
||||
action_dim = env.action_space.n
|
||||
agent = A2C(state_dim, action_dim, cfg)
|
||||
train(cfg,env,agent)
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
'''
|
||||
Author: John
|
||||
Author: JiangJi
|
||||
Email: johnjim0816@gmail.com
|
||||
Date: 2020-11-03 20:45:25
|
||||
LastEditor: John
|
||||
LastEditTime: 2021-03-20 17:41:33
|
||||
Date: 2021-05-03 21:38:54
|
||||
LastEditor: JiangJi
|
||||
LastEditTime: 2021-05-03 21:40:06
|
||||
Discription:
|
||||
Environment:
|
||||
'''
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from torch.distributions import Categorical
|
||||
|
||||
class ActorCritic(nn.Module):
|
||||
def __init__(self, state_dim, action_dim, hidden_dim=256):
|
||||
def __init__(self, num_inputs, num_outputs, hidden_size, std=0.0):
|
||||
super(ActorCritic, self).__init__()
|
||||
|
||||
self.critic = nn.Sequential(
|
||||
nn.Linear(state_dim, hidden_dim),
|
||||
nn.Linear(num_inputs, hidden_size),
|
||||
nn.ReLU(),
|
||||
nn.Linear(hidden_dim, 1)
|
||||
nn.Linear(hidden_size, 1)
|
||||
)
|
||||
|
||||
self.actor = nn.Sequential(
|
||||
nn.Linear(state_dim, hidden_dim),
|
||||
nn.Linear(num_inputs, hidden_size),
|
||||
nn.ReLU(),
|
||||
nn.Linear(hidden_dim, action_dim),
|
||||
nn.Linear(hidden_size, num_outputs),
|
||||
nn.Softmax(dim=1),
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
value = self.critic(x)
|
||||
print(x)
|
||||
probs = self.actor(x)
|
||||
dist = Categorical(probs)
|
||||
return dist, value
|
||||
@@ -1,153 +0,0 @@
|
||||
#This code is from openai baseline
|
||||
#https://github.com/openai/baselines/tree/master/baselines/common/vec_env
|
||||
|
||||
import numpy as np
|
||||
from multiprocessing import Process, Pipe
|
||||
|
||||
def worker(remote, parent_remote, env_fn_wrapper):
|
||||
parent_remote.close()
|
||||
env = env_fn_wrapper.x()
|
||||
while True:
|
||||
cmd, data = remote.recv()
|
||||
if cmd == 'step':
|
||||
ob, reward, done, info = env.step(data)
|
||||
if done:
|
||||
ob = env.reset()
|
||||
remote.send((ob, reward, done, info))
|
||||
elif cmd == 'reset':
|
||||
ob = env.reset()
|
||||
remote.send(ob)
|
||||
elif cmd == 'reset_task':
|
||||
ob = env.reset_task()
|
||||
remote.send(ob)
|
||||
elif cmd == 'close':
|
||||
remote.close()
|
||||
break
|
||||
elif cmd == 'get_spaces':
|
||||
remote.send((env.observation_space, env.action_space))
|
||||
else:
|
||||
raise NotImplementedError
|
||||
|
||||
class VecEnv(object):
|
||||
"""
|
||||
An abstract asynchronous, vectorized environment.
|
||||
"""
|
||||
def __init__(self, num_envs, observation_space, action_space):
|
||||
self.num_envs = num_envs
|
||||
self.observation_space = observation_space
|
||||
self.action_space = action_space
|
||||
|
||||
def reset(self):
|
||||
"""
|
||||
Reset all the environments and return an array of
|
||||
observations, or a tuple of observation arrays.
|
||||
If step_async is still doing work, that work will
|
||||
be cancelled and step_wait() should not be called
|
||||
until step_async() is invoked again.
|
||||
"""
|
||||
pass
|
||||
|
||||
def step_async(self, actions):
|
||||
"""
|
||||
Tell all the environments to start taking a step
|
||||
with the given actions.
|
||||
Call step_wait() to get the results of the step.
|
||||
You should not call this if a step_async run is
|
||||
already pending.
|
||||
"""
|
||||
pass
|
||||
|
||||
def step_wait(self):
|
||||
"""
|
||||
Wait for the step taken with step_async().
|
||||
Returns (obs, rews, dones, infos):
|
||||
- obs: an array of observations, or a tuple of
|
||||
arrays of observations.
|
||||
- rews: an array of rewards
|
||||
- dones: an array of "episode done" booleans
|
||||
- infos: a sequence of info objects
|
||||
"""
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
"""
|
||||
Clean up the environments' resources.
|
||||
"""
|
||||
pass
|
||||
|
||||
def step(self, actions):
|
||||
self.step_async(actions)
|
||||
return self.step_wait()
|
||||
|
||||
|
||||
class CloudpickleWrapper(object):
|
||||
"""
|
||||
Uses cloudpickle to serialize contents (otherwise multiprocessing tries to use pickle)
|
||||
"""
|
||||
def __init__(self, x):
|
||||
self.x = x
|
||||
def __getstate__(self):
|
||||
import cloudpickle
|
||||
return cloudpickle.dumps(self.x)
|
||||
def __setstate__(self, ob):
|
||||
import pickle
|
||||
self.x = pickle.loads(ob)
|
||||
|
||||
|
||||
class SubprocVecEnv(VecEnv):
|
||||
def __init__(self, env_fns, spaces=None):
|
||||
"""
|
||||
envs: list of gym environments to run in subprocesses
|
||||
"""
|
||||
self.waiting = False
|
||||
self.closed = False
|
||||
nenvs = len(env_fns)
|
||||
self.nenvs = nenvs
|
||||
self.remotes, self.work_remotes = zip(*[Pipe() for _ in range(nenvs)])
|
||||
self.ps = [Process(target=worker, args=(work_remote, remote, CloudpickleWrapper(env_fn)))
|
||||
for (work_remote, remote, env_fn) in zip(self.work_remotes, self.remotes, env_fns)]
|
||||
for p in self.ps:
|
||||
p.daemon = True # if the main process crashes, we should not cause things to hang
|
||||
p.start()
|
||||
for remote in self.work_remotes:
|
||||
remote.close()
|
||||
|
||||
self.remotes[0].send(('get_spaces', None))
|
||||
observation_space, action_space = self.remotes[0].recv()
|
||||
VecEnv.__init__(self, len(env_fns), observation_space, action_space)
|
||||
|
||||
def step_async(self, actions):
|
||||
for remote, action in zip(self.remotes, actions):
|
||||
remote.send(('step', action))
|
||||
self.waiting = True
|
||||
|
||||
def step_wait(self):
|
||||
results = [remote.recv() for remote in self.remotes]
|
||||
self.waiting = False
|
||||
obs, rews, dones, infos = zip(*results)
|
||||
return np.stack(obs), np.stack(rews), np.stack(dones), infos
|
||||
|
||||
def reset(self):
|
||||
for remote in self.remotes:
|
||||
remote.send(('reset', None))
|
||||
return np.stack([remote.recv() for remote in self.remotes])
|
||||
|
||||
def reset_task(self):
|
||||
for remote in self.remotes:
|
||||
remote.send(('reset_task', None))
|
||||
return np.stack([remote.recv() for remote in self.remotes])
|
||||
|
||||
def close(self):
|
||||
if self.closed:
|
||||
return
|
||||
if self.waiting:
|
||||
for remote in self.remotes:
|
||||
remote.recv()
|
||||
for remote in self.remotes:
|
||||
remote.send(('close', None))
|
||||
for p in self.ps:
|
||||
p.join()
|
||||
self.closed = True
|
||||
|
||||
def __len__(self):
|
||||
return self.nenvs
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 62 KiB |
120
codes/A2C/task0_train.py
Normal file
120
codes/A2C/task0_train.py
Normal file
@@ -0,0 +1,120 @@
|
||||
import sys,os
|
||||
curr_path = os.path.dirname(__file__)
|
||||
parent_path = os.path.dirname(curr_path)
|
||||
sys.path.append(parent_path) # add current terminal path to sys.path
|
||||
|
||||
|
||||
import gym
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.optim as optim
|
||||
import datetime
|
||||
from common.multiprocessing_env import SubprocVecEnv
|
||||
from A2C.model import ActorCritic
|
||||
from common.utils import save_results, make_dir
|
||||
from common.plot import plot_rewards
|
||||
|
||||
curr_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") # obtain current time
|
||||
class A2CConfig:
|
||||
def __init__(self) -> None:
|
||||
self.algo='A2C'
|
||||
self.env= 'CartPole-v0'
|
||||
self.result_path = curr_path+"/outputs/" +self.env+'/'+curr_time+'/results/' # path to save results
|
||||
self.model_path = curr_path+"/outputs/" +self.env+'/'+curr_time+'/models/' # path to save models
|
||||
self.n_envs = 8
|
||||
self.gamma = 0.99
|
||||
self.hidden_size = 256
|
||||
self.lr = 1e-3 # learning rate
|
||||
self.max_frames = 30000
|
||||
self.n_steps = 5
|
||||
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
def make_envs(env_name):
|
||||
def _thunk():
|
||||
env = gym.make(env_name)
|
||||
env.seed(2)
|
||||
return env
|
||||
return _thunk
|
||||
def test_env(env,model,vis=False):
|
||||
state = env.reset()
|
||||
if vis: env.render()
|
||||
done = False
|
||||
total_reward = 0
|
||||
while not done:
|
||||
state = torch.FloatTensor(state).unsqueeze(0).to(cfg.device)
|
||||
dist, _ = model(state)
|
||||
next_state, reward, done, _ = env.step(dist.sample().cpu().numpy()[0])
|
||||
state = next_state
|
||||
if vis: env.render()
|
||||
total_reward += reward
|
||||
return total_reward
|
||||
def compute_returns(next_value, rewards, masks, gamma=0.99):
|
||||
R = next_value
|
||||
returns = []
|
||||
for step in reversed(range(len(rewards))):
|
||||
R = rewards[step] + gamma * R * masks[step]
|
||||
returns.insert(0, R)
|
||||
return returns
|
||||
|
||||
|
||||
def train(cfg,envs):
|
||||
env = gym.make(cfg.env) # a single env
|
||||
env.seed(10)
|
||||
state_dim = envs.observation_space.shape[0]
|
||||
action_dim = envs.action_space.n
|
||||
model = ActorCritic(state_dim, action_dim, cfg.hidden_size).to(cfg.device)
|
||||
optimizer = optim.Adam(model.parameters())
|
||||
frame_idx = 0
|
||||
test_rewards = []
|
||||
test_ma_rewards = []
|
||||
state = envs.reset()
|
||||
while frame_idx < cfg.max_frames:
|
||||
log_probs = []
|
||||
values = []
|
||||
rewards = []
|
||||
masks = []
|
||||
entropy = 0
|
||||
# rollout trajectory
|
||||
for _ in range(cfg.n_steps):
|
||||
state = torch.FloatTensor(state).to(cfg.device)
|
||||
dist, value = model(state)
|
||||
action = dist.sample()
|
||||
next_state, reward, done, _ = envs.step(action.cpu().numpy())
|
||||
log_prob = dist.log_prob(action)
|
||||
entropy += dist.entropy().mean()
|
||||
log_probs.append(log_prob)
|
||||
values.append(value)
|
||||
rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(cfg.device))
|
||||
masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(cfg.device))
|
||||
state = next_state
|
||||
frame_idx += 1
|
||||
if frame_idx % 100 == 0:
|
||||
test_reward = np.mean([test_env(env,model) for _ in range(10)])
|
||||
print(f"frame_idx:{frame_idx}, test_reward:{test_reward}")
|
||||
test_rewards.append(test_reward)
|
||||
if test_ma_rewards:
|
||||
test_ma_rewards.append(0.9*test_ma_rewards[-1]+0.1*test_reward)
|
||||
else:
|
||||
test_ma_rewards.append(test_reward)
|
||||
# plot(frame_idx, test_rewards)
|
||||
next_state = torch.FloatTensor(next_state).to(cfg.device)
|
||||
_, next_value = model(next_state)
|
||||
returns = compute_returns(next_value, rewards, masks)
|
||||
log_probs = torch.cat(log_probs)
|
||||
returns = torch.cat(returns).detach()
|
||||
values = torch.cat(values)
|
||||
advantage = returns - values
|
||||
actor_loss = -(log_probs * advantage.detach()).mean()
|
||||
critic_loss = advantage.pow(2).mean()
|
||||
loss = actor_loss + 0.5 * critic_loss - 0.001 * entropy
|
||||
optimizer.zero_grad()
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
return test_rewards, test_ma_rewards
|
||||
if __name__ == "__main__":
|
||||
cfg = A2CConfig()
|
||||
envs = [make_envs(cfg.env) for i in range(cfg.n_envs)]
|
||||
envs = SubprocVecEnv(envs) # 8 env
|
||||
rewards,ma_rewards = train(cfg,envs)
|
||||
make_dir(cfg.result_path,cfg.model_path)
|
||||
save_results(rewards,ma_rewards,tag='train',path=cfg.result_path)
|
||||
plot_rewards(rewards,ma_rewards,tag="train",env=cfg.env,algo = cfg.algo,path=cfg.result_path)
|
||||
@@ -1,32 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
'''
|
||||
Author: John
|
||||
Email: johnjim0816@gmail.com
|
||||
Date: 2020-10-15 21:31:19
|
||||
LastEditor: John
|
||||
LastEditTime: 2020-11-03 17:05:48
|
||||
Discription:
|
||||
Environment:
|
||||
'''
|
||||
import os
|
||||
import numpy as np
|
||||
import datetime
|
||||
|
||||
SEQUENCE = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
SAVED_MODEL_PATH = os.path.split(os.path.abspath(__file__))[0]+"/saved_model/"+SEQUENCE+'/'
|
||||
RESULT_PATH = os.path.split(os.path.abspath(__file__))[0]+"/results/"+SEQUENCE+'/'
|
||||
|
||||
|
||||
def save_results(rewards,moving_average_rewards,ep_steps,path=RESULT_PATH):
|
||||
if not os.path.exists(path): # 检测是否存在文件夹
|
||||
os.mkdir(path)
|
||||
np.save(RESULT_PATH+'rewards_train.npy', rewards)
|
||||
np.save(RESULT_PATH+'moving_average_rewards_train.npy', moving_average_rewards)
|
||||
np.save(RESULT_PATH+'steps_train.npy',ep_steps )
|
||||
|
||||
def save_model(agent,model_path='./saved_model'):
|
||||
if not os.path.exists(model_path): # 检测是否存在文件夹
|
||||
os.mkdir(model_path)
|
||||
agent.save_model(model_path+'checkpoint.pth')
|
||||
print('model saved!')
|
||||
Reference in New Issue
Block a user