策略梯度算法在tim上变得更糟

2024-05-08 22:00:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着为视频游戏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')

但在我训练了我的网络之后,剧本的情节似乎表明网络在接近尾声时变得更糟了。同样在上一集中,所有训练示例的损失都是一样的(~0.68),当我尝试测试网络时,球员的球拍只是静止不动。有什么方法可以改进我的代码吗?你知道吗


Tags: importenvtfnppltactionspacetotal
1条回答
网友
1楼 · 发布于 2024-05-08 22:00:28

我想请你熟悉如何使用张量流编码神经网络,因为问题就在这里。您在两个nn层中都提供了activation=tf.nn.softmax,这两个nn层应该是一个终端层(因为您试图找到最大的动作概率)。您可以在第二层中将其更改为tf.nn.relulearning_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。你知道吗

相关问题 更多 >