我试图了解政策梯度如何工作,并建立一个乒乓游戏代理从草图使用Tensorflow,但似乎不起作用。我不确定我是否对政策梯度有误解。在这里我张贴我的解释代码。你知道吗
首先创建占位符来保存从environmant获取的输入帧
input_frame = tf.placeholder(tf.float32, [380*400, None], name='input_frame')
定义简单网络和模型的参数
W1 = tf.get_variable(name='w1', shape=[200, 380*400],initializer=tf.contrib.layers.xavier_initializer(seed=2))
b1 = tf.get_variable(name='b1', shape=[200, 1], initializer=tf.zeros_initializer())
W2 = tf.get_variable(name='w2', shape=[3, 200],initializer=tf.contrib.layers.xavier_initializer(seed=2))
b2 = tf.get_variable(name='b2', shape=[3, 1], initializer=tf.zeros_initializer())
def build_model():
L_1 =tf.nn.relu(tf.add(tf.matmul(W1, input_frame), b1))
L_2 =tf.nn.relu(tf.add(tf.matmul(W2, L_1), b2))
Y = tf.nn.softmax(L_2, axis=0)
return Y
折扣奖励函数
def discount_rewards(r):
discounted_r = np.zeros_like(r)
running_add = 0
for t in reversed(range(0, discounted_r.size)):
if r[t] != 0: running_add = 0
#https://github.com/hunkim/ReinforcementZeroToAll/issues/1
running_add = running_add * gamma + r[t]
discounted_r[t] = running_add
return discounted_r
建立模型
Y = build_model()
样品操作
sample_op = tf.multinomial(logits=tf.reshape(Y, (1, 3)), num_samples=1)
Y_action = sample_op - 1 #Move up: -1, stay still: 0, move down: 1
例行初始化
global_step = tf.train.get_or_create_global_step()
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
通过裁剪从环境中检索下一帧
next_frame = my_pong.get_next_frame().T[pong_game.SCOREBOARD_HEIGHT + 6 : pong_game.WINDOW_HEIGHT, 0 + pong_game.PADDLE_THICKNESS:pong_game.WINDOW_WIDTH - pong_game.PADDLE_THICKNESS].reshape(380*400, 1)
通过减去当前帧和最后一帧得到观察值
observation_ = next_frame - last_frame
action_ = sess.run(Y_action, feed_dict={
input_frame: observation_})
对于每一帧,通过输入采样的动作从环境中获得奖励,并附加情节记忆。你知道吗
done_, reward_ = my_pong.paddle_2_control(action_)
episode_menory.append((observation_, action_, float(reward_)))
last_frame = next_frame
如果一方得到21分,完成值为真,开始训练过程
先打折,再正常化奖励
if done_:
obs, lab, rwd = zip(*episode_menory)
prwd = discount_rewards(rwd)
prwd -= np.mean(prwd)
prwd /= np.std(prwd)
obs_reshape = np.squeeze(obs).T
使用本集中的示例动作构建一个热门标签
lab_one_hot = tf.one_hot(np.squeeze(lab)+1, 3, axis=0)
交叉熵损失。一个热标签是采样操作,而logits是模型的输出。(我不确定这是否正确)
cross_entropy = tf.losses.softmax_cross_entropy(onehot_labels=lab_one_hot, logits=Y)
通过将处理后的奖励“prwd”与损失的交叉熵相乘来定义成本函数
cost = cross_entropy * prwd
定义优化器并开始培训
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(cost)
_, cost_ = sess.run([train_op, cost], feed_dict={input_frame: obs_reshape})
episode_menory = []
print("Episode %d finish! Cost = %f" % (episode, np.sum(cost_)))
episode += 1
我在我的泰坦X设备上运行了一个周末的程序,但性能似乎没有任何改善。成本是随机输出的有时负有时正。我不知道如何从输出的成本值来衡量模型偏好。我不知道我错过了或弄错了哪一部分。非常感谢你。你知道吗
我在这里发布完整的代码:https://github.com/ivonchan0414/pg_pong
这里有丰富的(/复杂的)培训和反馈设置。我不能通过简单的随便检查来找出错误。你知道吗
隔离问题的方法可能是遵循典型的管道调试和验证过程:
此外:
相关问题 更多 >
编程相关推荐