boyu-ai / hands-on-rl Goto Github PK
View Code? Open in Web Editor NEWhttps://hrl.boyuai.com/
License: Apache License 2.0
https://hrl.boyuai.com/
License: Apache License 2.0
应该是
而不是 更新状态
更多可参考我项目:https://github.com/StevenJokess/d2rl/blob/master/chapter/SAC.md
QQ群交个朋友:171097552
付款表达感谢:
请问cql算法计算logexpsumQ(s,a)时为什么要减去对数概率
q1_unif = self.critic_1(tmp_states, random_unif_actions).view(-1, self.num_random, 1)#tmp unif q1torch.Size([320, 1]) torch.Size([64, 5, 1])
q2_unif = self.critic_2(tmp_states, random_unif_actions).view(-1, self.num_random, 1)#tmp unif q1
q1_curr = self.critic_1(tmp_states, random_curr_actions).view(-1, self.num_random, 1)#tmp curr q1当前模型做出的选择
q2_curr = self.critic_2(tmp_states, random_curr_actions).view(-1, self.num_random, 1)#tmp curr q2
q1_next = self.critic_1(tmp_states, random_next_actions).view(-1, self.num_random, 1)#tmp next q1
q2_next = self.critic_2(tmp_states, random_next_actions).view(-1, self.num_random, 1)#tmp next q2
q1_cat = torch.cat([q1_unif - random_unif_log_pi,q1_curr - random_curr_log_pi.detach().view(-1, self.num_random, 1),q1_next - random_next_log_pi.detach().view(-1, self.num_random, 1)],dim=1)#64 15 1
q2_cat = torch.cat([q2_unif - random_unif_log_pi,q2_curr - random_curr_log_pi.detach().view(-1, self.num_random, 1),q2_next - random_next_log_pi.detach().view(-1, self.num_random, 1)],dim=1)#64 15 1
qf1_loss_1 = torch.logsumexp(q1_cat, dim=1).mean()#这里对应的是18.3的第一项中的logsumexp,它对应的是s采取数据集中的,a采取随机动作的q值,接下来看q的取值
qf2_loss_1 = torch.logsumexp(q2_cat, dim=1).mean()
https://hrl.boyuai.com/chapter/2/sac%E7%AE%97%E6%B3%95#143-soft-%E7%AD%96%E7%95%A5%E8%BF%AD%E4%BB%A3
应该是,
其中,状态价值函数被写为
$$
V\left(s_t\right)=\mathbb{E}{a_t \sim \pi}\left[Q\left(s_t, a_t\right)-\alpha \log \pi\left(a_t \mid s_t\right)\right]=\mathbb{E}{a_t \sim \pi}\left[Q\left(s_t, a_t\right)\right]+\alpha H\left(\pi\left(\cdot \mid s_t\right)\right)
$$
原文漏掉了\alpha,
更多可参考我项目:https://github.com/StevenJokess/d2rl/blob/master/chapter/SAC.md
QQ群交个朋友:171097552
付款表达感谢:
本章Actor-Critic代码是在序列结束后才更新的,并没有体现Actor-Critic相比于REINFORCEMENT的优势:即可以单步更新,能够给出单步更新的Actor-Critic代码呀?
马尔可夫决策,使用蒙特卡罗估计状态价值时,为什么采样动作和状态的时候,temp是累积的呢?具体代码在3.5节sample函数中的temp+=1
第7章-DQN算法.ipynb 最后只给出了CNN卷积层的类,对于初学者依旧无法完整掌握,希望可否给出完整的基于图像训练DQN的代码,以供初学者学习
When utilizing the continuous PPO algorithm, it is not guaranteed that the action will always fall within the specified action space. The take_action() function requires revision.
https://hrl.boyuai.com/chapter/1/%E6%97%B6%E5%BA%8F%E5%B7%AE%E5%88%86%E7%AE%97%E6%B3%95#sarsa
在这篇文章的搜索”# 每10条序列打印一下这10条序列的平均回报“,可以找到这个代码注释
这里每个进度条内部是50个序列,所以这里面应该计算每50条序列的平均回报吧
https://hrl.boyuai.com/chapter/1/%E5%A4%9A%E8%87%82%E8%80%81%E8%99%8E%E6%9C%BA#25-%E4%B8%8A%E7%BD%AE%E4%BF%A1%E7%95%8C%E7%AE%97%E6%B3%95
中
应是 p = 1 / N。
其中,我们用$N$表示到目前为止按压所有臂的次数和,$N_t$代表为目前为止按压第t个臂的次数。
更多可参考我项目:https://github.com/StevenJokess/d2rl/blob/master/chapter/MAB.md#L124-L125
QQ群交个朋友:171097552
付款表达感谢:
第七章DQN代运行报错
ValueError Traceback (most recent call last)
Cell In[12], line 33
31 done = False
32 while not done:
---> 33 action = agent.take_action(state)
34 next_state, reward, done, _ = env.step(action)
35 replay_buffer.add(state, action, reward, next_state, done)
Cell In[9], line 24, in DQN.take_action(self, state)
22 action = np.random.randint(self.action_dim)
23 else:
---> 24 state = torch.tensor([state], dtype=torch.float).to(self.device)
25 action = self.q_net(state).argmax().item()
26 return action
ValueError: expected sequence of length 4 at dim 2 (got 0)
`
a
请问咱们的教程案例能拓展使用multiDiscrete 动作空间吗?
我是RL新手,最近遇到的问题需要同时输出两个动作,每个动作有
各自不同的维度。
比如动作1取值0, 1, 2;动作2取值0, 1。
请问这样的问题能基于咱们的DQN或者PPO章节去解决吗?
非常感谢!
作者您好,请问可以提供各个包的版本吗(如pytorch的版本、matplotlib的版本)
目前配环境matplotlib会经常和其他包冲突
中
应是动作$a_t$,$\underset{a \in \mathcal{A}}{\operatorname{argmax}} \hat{Q}_t(a)$
更多可参考我项目:https://github.com/StevenJokess/d2rl/blob/master/MAB.md
QQ群交个朋友:171097552
付款表达感谢:
def compute_return函数无法计算序列带环的情况 如状态序列s3-s4-s5-s3-s6
修改代码如下
def compute_return(start_index, chain, gamma): G = 0 for i in reversed(range( len(chain))): print("G = %f* %f + %d" %(gamma, G, rewards[chain[i] - 1] )) G = gamma * G + rewards[chain[i] - 1] print(i) return G
class CliffWalkingEnv:
...
def createP(self):
...
P[i * self.ncol + j][a] = [(1, i * self.ncol + j, 0,
True)]
如上面的代码中, 每个P[s][a]的值为都为[(p, next_state, reward, done)],
其中第一个值p永远为1, 它的作用是什么?
它并不是转移概率, 因为转移概率在PolicyIteration.pi中.
请问第一个恒为1的p值的作用是什么?
谢谢!
可否打包一个包含运行代码环境的docker镜像
Recently I've been reading the book for learning reinforcement learning. Thanks for such a wonderful tutorial with complete code! And I found that a concept is not clear for a RL beginner in chapter 3.3.2 价值函数.
here is the link: https://hrl.boyuai.com/chapter/1/%E9%A9%AC%E5%B0%94%E5%8F%AF%E5%A4%AB%E5%86%B3%E7%AD%96%E8%BF%87%E7%A8%8B#331-%E5%9B%9E%E6%8A%A5
The original version is:
在马尔可夫奖励过程中,一个状态的期望回报被称为这个状态的价值(value)。所有状态的价值就组成了价值函数(value function),价值函数的输入为某个状态,输出为这个状态的价值。
a little piece of advice is:
在马尔可夫奖励过程中,一个状态的期望回报(即从这个状态开始的未来期望累计回报)被称为这个状态的价值(value)。所有状态的价值就组成了价值函数(value function),价值函数的输入为某个状态,输出为这个状态的价值。
Hope this helps!
AttributeError Traceback (most recent call last)
Input In [35], in <cell line: 17>()
15 random.seed(0)
16 np.random.seed(0)
---> 17 env.seed(0)
18 torch.manual_seed(0)
19 replay_buffer = ReplayBuffer(buffer_size)
File ~/Application/anaconda3/envs/RL/lib/python3.9/site-packages/gym/core.py:241, in Wrapper.__getattr__(self, name)
239 if name.startswith("_"):
240 raise AttributeError(f"accessing private attribute '{name}' is prohibited")
--> 241 return getattr(self.env, name)
File ~/Application/anaconda3/envs/RL/lib/python3.9/site-packages/gym/core.py:241, in Wrapper.__getattr__(self, name)
239 if name.startswith("_"):
240 raise AttributeError(f"accessing private attribute '{name}' is prohibited")
--> 241 return getattr(self.env, name)
File ~/Application/anaconda3/envs/RL/lib/python3.9/site-packages/gym/core.py:241, in Wrapper.__getattr__(self, name)
239 if name.startswith("_"):
240 raise AttributeError(f"accessing private attribute '{name}' is prohibited")
--> 241 return getattr(self.env, name)
AttributeError: 'CartPoleEnv' object has no attribute 'seed'
我在运行第七章代码的时候有以下报错,应该怎么解决
https://hrl.boyuai.com/chapter/2/actor-critic%E7%AE%97%E6%B3%95#102-actor-critic
上图中的"不会产生梯度来更新价值函数"是什么意思?
谢谢!
在https://hrl.boyuai.com/chapter/2/actor-critic%E7%AE%97%E6%B3%95 看到有用这个工具包来做一些actor-critic 算法的迭代过程,不知道可以在哪里下载呢
for循环最内圈,qsa += p * (r + self.gamma * self.v[next_state] * (1 - done)),
r在for循环最内圈多次加和,根据公式: Q(s, a)=r+ gamma * sum(p * v(s'));
是不是应该放在for循环外只加一次?
第9章-策略梯度算法 中的交叉熵损失体现在代码哪里 ?
是log_prob = torch.log(self.policy_net(state).gather(1, action)) 这里吗 ?
请问网页版本和纸质书有区别吗,我看网页版本描述比较简洁,纸质书上也是这样吗?
作者您好!
在网站中的DDPG算法篇中
同样作为一种离线策略的算法,DDPG 在行为策略上引入一个随机噪声来进行探索。我们来看一下 DDPG 的具体算法流程吧!
这里我觉得应该是在线策略算法,麻烦您检查下!
换了不同的地图尺寸和智能体数目,训练速度都是CPU比GPU快1倍左右,而且使用GPU时显存占用都是870M,不随着地图尺寸和智能体数目改变。device确实是cuda,但显卡利用率一直是0%,请问是什么问题呢?
非常感谢!
在1.3节中公式
下一状态~P(.|当前状态,智能体动作)
其中当前状态是指当前智能体的当前状态还是变化环境的当前状态,或者两者都有
https://hrl.boyuai.com/chapter/1/dyna-q%E7%AE%97%E6%B3%95
” 而本节课程中即将介绍的 Dyna-Q 算法也是非常基础的基于模型的强化学习方法,它的环境模型是通过估计得到。“
Dyna-Q 算法 应该是无模型的强化学习方法,是不是笔误写错了
https://hrl.boyuai.com/chapter/1/%E9%A9%AC%E5%B0%94%E5%8F%AF%E5%A4%AB%E5%86%B3%E7%AD%96%E8%BF%87%E7%A8%8B#35-%E8%92%99%E7%89%B9%E5%8D%A1%E6%B4%9B%E6%96%B9%E6%B3%95
在《动手学强化学习》3.5蒙特卡洛方法中,
上面这里说到是在一个策略下的函数,下面的函数却没有考虑策略。在课件中的公式比较准确:
建议修改。
class PolicyIteration:
def policy_evaluation(self): # 策略评估
...
for a in range(4):
qsa = 0
for res in self.env.P[s][a]: //**为什么这里又用一个循环?**
p, next_state, r, done = res
qsa += p * (r + self.gamma * self.v[next_state] * (1 - done))
# 本章环境比较特殊,奖励和下一个状态有关,所以需要和状态转移概率相乘
qsa_list.append(self.pi[s][a] * qsa)
上面的第二个for循环代码是没有意义的, 因为self.env.P[s][a]中永远只有一个值[(p, next_state, reward, done)].
所以可以改为如下代码:
for a in range(4):
p, next_state, r, done = self.env.P[s][a][0]
qsa = p * (r + self.gamma * self.v[next_state] * (1 - done))
# 本章环境比较特殊,奖励和下一个状态有关,所以需要和状态转移概率相乘
qsa_list.append(self.pi[s][a] * qsa)
修改后的结果和修改前是完全一致的.
谢谢!
在运行第5个代码块时,报出错误ValueError: expected sequence of length 4 at dim 2 (got 0),完整提示如下:
`ValueError Traceback (most recent call last)
f:\Codefield\jupyter_workspace\deeplearn\rl\Hands-on-RL\第7章-DQN算法.ipynb 单元格 5 in <cell line: 26>()
31 done = False
32 while not done:
---> 33 action = agent.take_action(state) # 根据状态state作出动作action
34 next_state, reward, done, _ = env.step(action) # 实际探索
35 replay_buffer.add(state, action, reward, next_state, done) # 将(状态,动作,奖励,下个状态,done)放入缓冲池
f:\Codefield\jupyter_workspace\deeplearn\rl\Hands-on-RL\第7章-DQN算法.ipynb 单元格 5 in DQN.take_action(self, state)
22 action = np.random.randint(self.action_dim)
23 else:# 利用
---> 24 state = torch.tensor([state], dtype=torch.float).to(self.device)
25 action = self.q_net(state).argmax().item() # 选取分数最大的那个动作,然后item函数转为python内置的数字类型
26 return action
ValueError: expected sequence of length 4 at dim 2 (got 0)`
我只是添加了注释,并没有修改任何代码。按道理来说,作为一本教科书,除非是版本问题导致的,否则不应该出现这种错误
在介绍Dueling DQN的部分,描述到”在同一个状态下,所有动作的优势值之和为 0,因为所有动作的动作价值的期望就是这个状态的状态价值。“,我的理解是所有动作的优势值在策略 pi 下的期望为0,而不是之和为0?不知道我的理解有没有问题。
阅读纸书时发现代码块 class DecayingEpsilonGreedy 有缩进/排版错误, return k 应属于 run_one_step 函数,即少了一层缩进。同时发现网页版本中也存在此问题,故在此提 issue ,供参考。
注:
https://hrl.boyuai.com/chapter/2/dqn%E7%AE%97%E6%B3%95/#73-dqn
“假设神经网络用来拟合函数w的参数是” 应为 "假设神经网络用来拟合函数的参数是w".
谢谢!
您好,在“第3章-马尔可夫决策过程”的采样函数部分我有一点疑问:
“在状态s下根据策略选择动作”处具体是怎样一个选择逻辑呢?
根据代码
for a_opt in A:
temp += Pi.get(join(s, a_opt), 0)
if temp > rand:
a = a_opt
我的理解是:“temp作为(s, a)策略的概率的总和,当某动作对应的策略计算概率总和后超过随机数rand,则选取此动作为选择的动作。“但若按此理解或许有些牵强,不知此处代码编写究竟是什么原因,还请您指教。采样函数整体代码函数如下,感谢。
def sample(MDP, Pi, timestep_max, number):
''' 采样函数,策略Pi,限制最长时间步timestep_max,总共采样序列数number '''
S, A, P, R, gamma = MDP
episodes = []
for _ in range(number):
episode = []
timestep = 0
s = S[np.random.randint(4)] # 随机选择一个除s5以外的状态s作为起点
# 当前状态为终止状态或者时间步太长时,一次采样结束
while s != "s5" and timestep <= timestep_max:
timestep += 1
rand, temp = np.random.rand(), 0
# 在状态s下根据策略选择动作
for a_opt in A:
temp += Pi.get(join(s, a_opt), 0)
if temp > rand:
a = a_opt
r = R.get(join(s, a), 0)
break
rand, temp = np.random.rand(), 0
# 根据状态转移概率得到下一个状态s_next
for s_opt in S:
temp += P.get(join(join(s, a), s_opt), 0)
if temp > rand:
s_next = s_opt
break
episode.append((s, a, r, s_next)) # 把(s,a,r,s_next)元组放入序列中
s = s_next # s_next变成当前状态,开始接下来的循环
episodes.append(episode)
return episodes
马尔可夫决策过程 第三行:
马尔可夫决策过程 (Markov Reward Decision Process) 是强化学习的基础。
比如DDPG和SAC
How to deal this? In SAC training.
老师好,关于代码有点问题想请教。在REINFORCE类下的update函数,模型更新代码如下
def update(self, transition_dict):
reward_list = transition_dict['rewards']
state_list = transition_dict['states']
action_list = transition_dict['actions']
G = 0
self.optimizer.zero_grad()
for i in reversed(range(len(reward_list))): # 从最后一步算起
reward = reward_list[i]
state = torch.tensor([state_list[i]], dtype=torch.float).to(self.device)
action = torch.tensor([action_list[i]]).view(-1, 1).to(self.device)
log_prob = torch.log(self.policy_net(state).gather(1, action))
G = self.gamma * G + reward
loss = -log_prob * G # 每一步的损失函数
loss.backward() # 反向传播计算梯度
self.optimizer.step() # 梯度下降
我的问题:请问为何optimizer.step是放在循环外面而不是里面?以及loss.backward()为何放在里面而不是外面?
放在外面的话,相当于只更新最后一个循环的loss.backward()计算的梯度。那为何还要每个循环都执行loss.backward(),而不是把loss.backward()放在外面?
感谢解答~
# 计算tanh_normal分布的对数概率密度
log_prob = log_prob - torch.log(1 - torch.tanh(action).pow(2) + 1e-7)
根据公式来看,其中不需要再对action
,再执行一次tanh
了。
你好,请问在第七章DQN算法中,DQN类的update方法中,dones的具体含义是什么?
我的理解是:dones列表示该动作序列是否达到最终状态,达到为1,未达到为0,故在以下语句中:
q_targets = rewards + self.gamma * max_next_q_values * (1 - dones
)
最后要加上(1-dones)来做调节
不知我理解的是否正确。
盼回复
在Class EnsembleModel类中 trian()方法里,有如下代码:
def train(self, loss):
self.optimizer.zero_grad()
loss += 0.01 * torch.sum(self._max_logvar) - 0.01 * torch.sum(
self._min_logvar)
loss.backward()
self.optimizer.step()
其中loss的定义看上去是将_max_logvar和_min_logvar进行加权平均。
在之前的代码中只定义了_max_logvar和_min_logvar的初始化。
这是否表明这两个参数仅仅靠加权后的loss进行反向传播,然后用optimizer.step()来进行迭代计算?
这种方法的目标是否为:多次迭代后,_max_logvar和_min_logvar将会逐渐接近真实值?
盼回复,多谢
本来的算法中是没有这个因子的,这么做是因为最终状态没有下一个状态了,所以Q是0吗?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.