我试图为电子游戏Pong编写策略梯度算法。 这是代码:
import tensorflow as tf
import gym
import numpy as np
import matplotlib.pyplot as plt
from os import getcwd
num_episodes = 1000
learning_rate = 0.01
rewards = []
env_name = 'Pong-v0'
env = gym.make(env_name)
x = tf.placeholder(tf.float32,(None,)+env.observation_space.shape)
y = tf.placeholder(tf.float32,(None,env.action_space.n))
def net(x):
layer1 = tf.layers.flatten(x)
layer2 = tf.layers.dense(layer1,200,activation=tf.nn.softmax)
layer3 = tf.layers.dense(layer2,env.action_space.n,activation=tf.nn.softmax)
return layer3
logits = net(x)
loss = tf.losses.sigmoid_cross_entropy(y,logits)
train = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
saver = tf.train.Saver()
init = tf.global_variables_initializer()
sess = tf.Session()
with tf.device('/device:GPU:0'):
sess.run(init)
for episode in range(num_episodes):
print('episode:',episode+1)
total_reward = 0
losses = []
training_data = []
observation = env.reset()
while True:
if max(0.1, (episode+1)/num_episodes) > np.random.uniform():
probs = sess.run(logits,feed_dict={x:[observation]})[0]
action = np.argmax(probs)
else:
action = env.action_space.sample()
onehot = np.zeros(env.action_space.n)
onehot[action] = 1
training_data.append([observation,onehot])
observation, reward, done, _ = env.step(action)
total_reward += reward
if done:
break
if total_reward >= 0:
learning_rate = 0.01
else:
learning_rate = -0.01
for sample in training_data:
l,_ = sess.run([loss,train],feed_dict={x:[sample[0]], y:[sample[1]]})
losses.append(l)
print('loss:',l)
print('average loss:',sum(losses)/len(losses))
saver.save(sess,getcwd()+'/model.ckpt')
rewards.append(total_reward)
plt.plot(range(episode+1),rewards)
plt.ylabel('total reward')
plt.xlabel('episodes')
plt.savefig(getcwd()+'/reward_plot.png')
但是,在我训练了Network之后,脚本所做的绘图似乎暗示着Network到最后会变得更糟。同样在上一集中,所有训练示例的损失都相同(〜0.68),当我尝试测试网络时,播放器的拨片只是静止不动地坐在那里。有什么办法可以改善我的代码?
答案 0 :(得分:1)
我想请您熟悉如何使用Tensorflow编码神经网络,因为这存在问题所在。您在应该作为终端层的nn层中都提供activation=tf.nn.softmax
(因为您正在尝试找到最大的操作概率)。您可以在第二层将其更改为tf.nn.relu
。 learning_rate
有一个更大的问题:
if total_reward >= 0:
learning_rate = 0.01
else:
learning_rate = -0.01
Negative learning rate makes absolutely no sense。您希望学习率是正的(现在可以使用常数0.01)。
另外,另一条评论是,您没有提到observation_space
形状,但我将假定它是2D矩阵。然后,您可以在将其输入x
之前对其进行重塑。因此,您不需要不必要地使用tf.flatten
。