哈哈初学,复现龙龙老师的实例!
state:是平衡小车上的杆子,观测状态由 4 个连续的参数组成:推车位置 [-2.4,2.4],车速 [-∞,∞],杆子角度 [~-41.8°,~41.8°] 与杆子末端速度 [-∞,∞]。
游戏结束:当极点与垂直方向的夹角超过15度时,或者推车从中心移出2.4个单位以上
向推车施加+1或-1的力来控制系统
杆保持直立的每个时间步长都提供+1的奖励
代码分析
经验池缓存
批训练条件:
Transition = namedtuple('Transition', ['state', 'action', 'a_log_prob', 'reward', 'next_state'])
trans = Transition(state, action, action_prob, reward, next_state)
agent.store_transition(trans)
self.buffer.append(transition)
if done: # 合适的时间点训练网络(回合结束done=True才训练)
if len(agent.buffer) >= batch_size:
agent.optimize() # 训练网络
break
数据迭代次数:round()函数不设四舍五入位数,默认计算到整数。
# 对缓冲池数据大致迭代10遍
for _ in range(round(10*len(self.buffer)/batch_size)):
奖励计算
Rs = []
for r in reward[::-1]:
R = r + gamma * R
Rs.insert(0, R) #在List 列表前添加新的R
Rs = tf.constant(Rs, dtype=tf.float32) #将List转换为Tensor格式
重要性采样:old_action_log_prob为Actor策略网络得出的已经生成的buffer动作概率(策略采样offline);pi_a为index对应的(历史)buffer中的状态再进行Actor网络在线得出的动作概率(目标策略online)
ratio = (pi_a / tf.gather(old_action_log_prob, index, axis=0))
PPO2误差:
ratio = (pi_a / tf.gather(old_action_log_prob, index, axis=0))
surr1 = ratio * advantage
surr2 = tf.clip_by_value(ratio, 1 - epsilon, 1 + epsilon) * advantage
# PPO误差函数
policy_loss = -tf.reduce_mean(tf.minimum(surr1, surr2))
函数备注:
tf.reshape(tensor,[-1,1])将张量变为一维列向量
tf.reshape(tensor,[1,-1])将张量变为一维行向量
tf.gather 可以根据索引号收集数据的目的。
如:考虑班级成绩册的例子,共有 4 个班
级,每个班级 35 个学生,8 门科目,保存成绩册的张量 shape 为[4,35,8]。例如在班级的维度上面我们可以像下面这样收集1和2班级的成绩册。
x = tf.random.uniform([4,35,8],maxval=100,dtype=tf.int32)
y=tf.gather(x,[0,1],axis=0)
buffer.append(transition) 在列表后面添加存储数据。
range()返回从0到4的5个数构成的list,而arange()返回一个array对象。不过他们的元素都是一样的。
Transition = namedtuple('Transition', ['state', 'action', 'a_log_prob', 'reward', 'next_state'])
下面的函数的作用为从数组x中取出n个元素,false表示每个元素不一样
**np.random.choice**(x,n,replace=false)
np.arange(len(self.buffer)) :生成长度的数组,这里为0~