update
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
# DQN
|
||||
|
||||
## 原理简介
|
||||
DQN是Q-leanning算法的优化和延伸,Q-leaning中使用有限的Q表存储值的信息,而DQN中则用神经网络替代Q表存储信息,这样更适用于高维的情况,相关知识基础可参考[datawhale李宏毅笔记-Q学习](https://datawhalechina.github.io/leedeeprl-notes/#/chapter6/chapter6)。
|
||||
DQN是Q-leanning算法的优化和延伸,Q-leaning中使用有限的Q表存储值的信息,而DQN中则用神经网络替代Q表存储信息,这样更适用于高维的情况,相关知识基础可参考[datawhale李宏毅笔记-Q学习](https://datawhalechina.github.io/easy-rl/#/chapter6/chapter6)。
|
||||
|
||||
论文方面主要可以参考两篇,一篇就是2013年谷歌DeepMind团队的[Playing Atari with Deep Reinforcement Learning](https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf),一篇是也是他们团队后来在Nature杂志上发表的[Human-level control through deep reinforcement learning](https://web.stanford.edu/class/psych209/Readings/MnihEtAlHassibis15NatureControlDeepRL.pdf)。后者在算法层面增加target q-net,也可以叫做Nature DQN。
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
@Email: johnjim0816@gmail.com
|
||||
@Date: 2020-06-12 00:50:49
|
||||
@LastEditor: John
|
||||
LastEditTime: 2021-03-13 14:56:23
|
||||
LastEditTime: 2021-03-30 17:01:26
|
||||
@Discription:
|
||||
@Environment: python 3.7.7
|
||||
'''
|
||||
@@ -13,6 +13,8 @@ LastEditTime: 2021-03-13 14:56:23
|
||||
'''
|
||||
|
||||
|
||||
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.optim as optim
|
||||
@@ -23,61 +25,44 @@ from common.memory import ReplayBuffer
|
||||
from common.model import MLP
|
||||
class DQN:
|
||||
def __init__(self, state_dim, action_dim, cfg):
|
||||
|
||||
|
||||
self.action_dim = action_dim # 总的动作个数
|
||||
self.device = cfg.device # 设备,cpu或gpu等
|
||||
self.gamma = cfg.gamma # 奖励的折扣因子
|
||||
self.gamma = cfg.gamma # 奖励的折扣因子
|
||||
# e-greedy策略相关参数
|
||||
self.sample_count = 0 # 用于epsilon的衰减计数
|
||||
self.epsilon = 0
|
||||
self.epsilon_start = cfg.epsilon_start
|
||||
self.epsilon_end = cfg.epsilon_end
|
||||
self.epsilon_decay = cfg.epsilon_decay
|
||||
self.frame_idx = 0 # 用于epsilon的衰减计数
|
||||
self.epsilon = lambda frame_idx: cfg.epsilon_end + \
|
||||
(cfg.epsilon_start - cfg.epsilon_end) * \
|
||||
math.exp(-1. * frame_idx / cfg.epsilon_decay)
|
||||
self.batch_size = cfg.batch_size
|
||||
self.policy_net = MLP(state_dim, action_dim,hidden_dim=cfg.hidden_dim).to(self.device)
|
||||
self.target_net = MLP(state_dim, action_dim,hidden_dim=cfg.hidden_dim).to(self.device)
|
||||
# target_net的初始模型参数完全复制policy_net
|
||||
self.target_net.load_state_dict(self.policy_net.state_dict())
|
||||
self.target_net.eval() # 不启用 BatchNormalization 和 Dropout
|
||||
# 可查parameters()与state_dict()的区别,前者require_grad=True
|
||||
self.policy_net = MLP(state_dim, action_dim,
|
||||
hidden_dim=cfg.hidden_dim).to(self.device)
|
||||
self.target_net = MLP(state_dim, action_dim,
|
||||
hidden_dim=cfg.hidden_dim).to(self.device)
|
||||
self.optimizer = optim.Adam(self.policy_net.parameters(), lr=cfg.lr)
|
||||
self.loss = 0
|
||||
self.memory = ReplayBuffer(cfg.memory_capacity)
|
||||
|
||||
def choose_action(self, state, train=True):
|
||||
def choose_action(self, state):
|
||||
'''选择动作
|
||||
'''
|
||||
if train:
|
||||
self.epsilon = self.epsilon_end + (self.epsilon_start - self.epsilon_end) * \
|
||||
math.exp(-1. * self.sample_count / self.epsilon_decay)
|
||||
self.sample_count += 1
|
||||
if random.random() > self.epsilon:
|
||||
with torch.no_grad():
|
||||
# 先转为张量便于丢给神经网络,state元素数据原本为float64
|
||||
# 注意state=torch.tensor(state).unsqueeze(0)跟state=torch.tensor([state])等价
|
||||
state = torch.tensor(
|
||||
[state], device=self.device, dtype=torch.float32)
|
||||
# 如tensor([[-0.0798, -0.0079]], grad_fn=<AddmmBackward>)
|
||||
q_value = self.policy_net(state)
|
||||
# tensor.max(1)返回每行的最大值以及对应的下标,
|
||||
# 如torch.return_types.max(values=tensor([10.3587]),indices=tensor([0]))
|
||||
# 所以tensor.max(1)[1]返回最大值对应的下标,即action
|
||||
action = q_value.max(1)[1].item()
|
||||
else:
|
||||
action = random.randrange(self.action_dim)
|
||||
return action
|
||||
else:
|
||||
with torch.no_grad(): # 取消保存梯度
|
||||
# 先转为张量便于丢给神经网络,state元素数据原本为float64
|
||||
# 注意state=torch.tensor(state).unsqueeze(0)跟state=torch.tensor([state])等价
|
||||
state = torch.tensor(
|
||||
[state], device='cpu', dtype=torch.float32) # 如tensor([[-0.0798, -0.0079]], grad_fn=<AddmmBackward>)
|
||||
q_value = self.target_net(state)
|
||||
# tensor.max(1)返回每行的最大值以及对应的下标,
|
||||
# 如torch.return_types.max(values=tensor([10.3587]),indices=tensor([0]))
|
||||
# 所以tensor.max(1)[1]返回最大值对应的下标,即action
|
||||
action = q_value.max(1)[1].item()
|
||||
return action
|
||||
self.frame_idx += 1
|
||||
if random.random() > self.epsilon(self.frame_idx):
|
||||
with torch.no_grad():
|
||||
# 先转为张量便于丢给神经网络,state元素数据原本为float64
|
||||
# 注意state=torch.tensor(state).unsqueeze(0)跟state=torch.tensor([state])等价
|
||||
state = torch.tensor(
|
||||
[state], device=self.device, dtype=torch.float32)
|
||||
# 如tensor([[-0.0798, -0.0079]], grad_fn=<AddmmBackward>)
|
||||
q_value = self.policy_net(state)
|
||||
# tensor.max(1)返回每行的最大值以及对应的下标,
|
||||
# 如torch.return_types.max(values=tensor([10.3587]),indices=tensor([0]))
|
||||
# 所以tensor.max(1)[1]返回最大值对应的下标,即action
|
||||
action = q_value.max(1)[1].item()
|
||||
else:
|
||||
action = random.randrange(self.action_dim)
|
||||
return action
|
||||
|
||||
def update(self):
|
||||
|
||||
if len(self.memory) < self.batch_size:
|
||||
@@ -96,32 +81,31 @@ class DQN:
|
||||
next_state_batch = torch.tensor(
|
||||
next_state_batch, device=self.device, dtype=torch.float)
|
||||
done_batch = torch.tensor(np.float32(
|
||||
done_batch), device=self.device).unsqueeze(1) # 将bool转为float然后转为张量
|
||||
done_batch), device=self.device)
|
||||
|
||||
'''计算当前(s_t,a)对应的Q(s_t, a)'''
|
||||
'''torch.gather:对于a=torch.Tensor([[1,2],[3,4]]),那么a.gather(1,torch.Tensor([[0],[1]]))=torch.Tensor([[1],[3]])'''
|
||||
q_values = self.policy_net(state_batch).gather(
|
||||
dim=1, index=action_batch) # 等价于self.forward
|
||||
# 计算所有next states的V(s_{t+1}),即通过target_net中选取reward最大的对应states
|
||||
next_state_values = self.target_net(
|
||||
next_state_batch).max(1)[0].detach() # 比如tensor([ 0.0060, -0.0171,...,])
|
||||
next_q_values = self.target_net(next_state_batch).max(
|
||||
1)[0].detach() # 比如tensor([ 0.0060, -0.0171,...,])
|
||||
# 计算 expected_q_value
|
||||
# 对于终止状态,此时done_batch[0]=1, 对应的expected_q_value等于reward
|
||||
expected_q_values = reward_batch + self.gamma * \
|
||||
next_state_values * (1-done_batch[0])
|
||||
expected_q_values = reward_batch + \
|
||||
self.gamma * next_q_values * (1-done_batch)
|
||||
# self.loss = F.smooth_l1_loss(q_values,expected_q_values.unsqueeze(1)) # 计算 Huber loss
|
||||
self.loss = nn.MSELoss()(q_values, expected_q_values.unsqueeze(1)) # 计算 均方误差loss
|
||||
# 优化模型
|
||||
self.optimizer.zero_grad() # zero_grad清除上一步所有旧的gradients from the last step
|
||||
# loss.backward()使用backpropagation计算loss相对于所有parameters(需要gradients)的微分
|
||||
self.loss.backward()
|
||||
for param in self.policy_net.parameters(): # clip防止梯度爆炸
|
||||
param.grad.data.clamp_(-1, 1)
|
||||
|
||||
# for param in self.policy_net.parameters(): # clip防止梯度爆炸
|
||||
# param.grad.data.clamp_(-1, 1)
|
||||
self.optimizer.step() # 更新模型
|
||||
|
||||
def save(self,path):
|
||||
def save(self, path):
|
||||
torch.save(self.target_net.state_dict(), path+'dqn_checkpoint.pth')
|
||||
|
||||
def load(self,path):
|
||||
self.target_net.load_state_dict(torch.load(path+'dqn_checkpoint.pth'))
|
||||
def load(self, path):
|
||||
self.target_net.load_state_dict(torch.load(path+'dqn_checkpoint.pth'))
|
||||
|
||||
467
codes/DQN/main.ipynb
Normal file
467
codes/DQN/main.ipynb
Normal file
File diff suppressed because one or more lines are too long
@@ -5,12 +5,17 @@
|
||||
@Email: johnjim0816@gmail.com
|
||||
@Date: 2020-06-12 00:48:57
|
||||
@LastEditor: John
|
||||
LastEditTime: 2021-03-26 17:17:17
|
||||
LastEditTime: 2021-03-30 16:59:19
|
||||
@Discription:
|
||||
@Environment: python 3.7.7
|
||||
'''
|
||||
import sys,os
|
||||
sys.path.append(os.getcwd()) # 添加当前终端路径
|
||||
from pathlib import Path
|
||||
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 torch
|
||||
import datetime
|
||||
@@ -18,58 +23,52 @@ from DQN.agent import DQN
|
||||
from common.plot import plot_rewards
|
||||
from common.utils import save_results
|
||||
|
||||
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): # 检测是否存在文件夹
|
||||
SEQUENCE = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") # obtain current time
|
||||
SAVED_MODEL_PATH = curr_path+"/saved_model/"+SEQUENCE+'/' # path to save model
|
||||
if not os.path.exists(curr_path+"/saved_model/"):
|
||||
os.mkdir(curr_path+"/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): # 检测是否存在文件夹
|
||||
RESULT_PATH = curr_path+"/results/"+SEQUENCE+'/' # path to save rewards
|
||||
if not os.path.exists(curr_path+"/results/"):
|
||||
os.mkdir(curr_path+"/results/")
|
||||
if not os.path.exists(RESULT_PATH):
|
||||
os.mkdir(RESULT_PATH)
|
||||
|
||||
class DQNConfig:
|
||||
def __init__(self):
|
||||
self.algo = "DQN" # 算法名称
|
||||
self.gamma = 0.99
|
||||
self.epsilon_start = 0.95 # e-greedy策略的初始epsilon
|
||||
self.algo = "DQN" # name of algo
|
||||
self.gamma = 0.95
|
||||
self.epsilon_start = 1 # e-greedy策略的初始epsilon
|
||||
self.epsilon_end = 0.01
|
||||
self.epsilon_decay = 200
|
||||
self.lr = 0.01 # 学习率
|
||||
self.memory_capacity = 800 # Replay Memory容量
|
||||
self.batch_size = 64
|
||||
self.epsilon_decay = 500
|
||||
self.lr = 0.0001 # learning rate
|
||||
self.memory_capacity = 10000 # Replay Memory容量
|
||||
self.batch_size = 32
|
||||
self.train_eps = 300 # 训练的episode数目
|
||||
self.train_steps = 200 # 训练每个episode的最大长度
|
||||
self.target_update = 2 # target net的更新频率
|
||||
self.eval_eps = 20 # 测试的episode数目
|
||||
self.eval_steps = 200 # 测试每个episode的最大长度
|
||||
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # 检测gpu
|
||||
self.hidden_dim = 128 # 神经网络隐藏层维度
|
||||
self.hidden_dim = 256 # 神经网络隐藏层维度
|
||||
|
||||
def train(cfg,env,agent):
|
||||
print('Start to train !')
|
||||
rewards = []
|
||||
ma_rewards = [] # 滑动平均的reward
|
||||
ep_steps = []
|
||||
ma_rewards = [] # moveing average reward
|
||||
for i_episode in range(cfg.train_eps):
|
||||
state = env.reset() # reset环境状态
|
||||
state = env.reset()
|
||||
done = False
|
||||
ep_reward = 0
|
||||
for i_step in range(cfg.train_steps):
|
||||
action = agent.choose_action(state) # 根据当前环境state选择action
|
||||
next_state, reward, done, _ = env.step(action) # 更新环境参数
|
||||
while not done:
|
||||
action = agent.choose_action(state)
|
||||
next_state, reward, done, _ = env.step(action)
|
||||
ep_reward += reward
|
||||
agent.memory.push(state, action, reward, next_state, done) # 将state等这些transition存入memory
|
||||
state = next_state # 跳转到下一个状态
|
||||
agent.update() # 每步更新网络
|
||||
if done:
|
||||
break
|
||||
# 更新target network,复制DQN中的所有weights and biases
|
||||
agent.memory.push(state, action, reward, next_state, done)
|
||||
state = next_state
|
||||
agent.update()
|
||||
if i_episode % cfg.target_update == 0:
|
||||
agent.target_net.load_state_dict(agent.policy_net.state_dict())
|
||||
print('Episode:{}/{}, Reward:{}, Steps:{}, Done:{}'.format(i_episode+1,cfg.train_eps,ep_reward,i_step+1,done))
|
||||
ep_steps.append(i_step)
|
||||
print('Episode:{}/{}, Reward:{}'.format(i_episode+1,cfg.train_eps,ep_reward))
|
||||
rewards.append(ep_reward)
|
||||
# 计算滑动窗口的reward
|
||||
if ma_rewards:
|
||||
@@ -82,8 +81,8 @@ def train(cfg,env,agent):
|
||||
|
||||
if __name__ == "__main__":
|
||||
cfg = DQNConfig()
|
||||
env = gym.make('CartPole-v0').unwrapped # 可google为什么unwrapped gym,此处一般不需要
|
||||
env.seed(1) # 设置env随机种子
|
||||
env = gym.make('CartPole-v0')
|
||||
env.seed(1)
|
||||
state_dim = env.observation_space.shape[0]
|
||||
action_dim = env.action_space.n
|
||||
agent = DQN(state_dim,action_dim,cfg)
|
||||
|
||||
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 58 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 27 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 66 KiB |
Binary file not shown.
BIN
codes/DQN/results/20210330-150205/ma_rewards_train.npy
Normal file
BIN
codes/DQN/results/20210330-150205/ma_rewards_train.npy
Normal file
Binary file not shown.
BIN
codes/DQN/results/20210330-150205/rewards_curve_train.png
Normal file
BIN
codes/DQN/results/20210330-150205/rewards_curve_train.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 50 KiB |
BIN
codes/DQN/results/20210330-150205/rewards_train.npy
Normal file
BIN
codes/DQN/results/20210330-150205/rewards_train.npy
Normal file
Binary file not shown.
BIN
codes/DQN/results/20210330-165925/ma_rewards_train.npy
Normal file
BIN
codes/DQN/results/20210330-165925/ma_rewards_train.npy
Normal file
Binary file not shown.
BIN
codes/DQN/results/20210330-165925/rewards_curve_train.png
Normal file
BIN
codes/DQN/results/20210330-165925/rewards_curve_train.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
BIN
codes/DQN/results/20210330-165925/rewards_train.npy
Normal file
BIN
codes/DQN/results/20210330-165925/rewards_train.npy
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
codes/DQN/saved_model/20210330-150205/dqn_checkpoint.pth
Normal file
BIN
codes/DQN/saved_model/20210330-150205/dqn_checkpoint.pth
Normal file
Binary file not shown.
BIN
codes/DQN/saved_model/20210330-165925/dqn_checkpoint.pth
Normal file
BIN
codes/DQN/saved_model/20210330-165925/dqn_checkpoint.pth
Normal file
Binary file not shown.
Reference in New Issue
Block a user