如何改进策略梯度的 tensorflow 2.0 代码?

数据挖掘 张量流 强化学习 政策梯度
2022-02-22 15:09:39

我重新创建了一些我在网上找到的代码,用于使用策略梯度解决强盗问题。该示例在 tensorflow 1.0 中,因此我使用 tensorflow 2.0 使用急切执行和梯度磁带重新创建它,但是,在训练模型时,我必须将权重 Tensor 转换为 numpy 数组,更新权重然后重新分配 tf.Variable 从numpy 数组。我觉得这不是性能,可以找到更好的方法。完整代码在这里https://github.com/entrpn/reinforcement-learning/blob/master/tf2_rl/bandits.py

我希望改进的主要代码如下:

def train(agent,action,reward, learning_rate=0.001):
    with tf.GradientTape() as t:
        current_loss = loss(agent(action),reward)
    dW = t.gradient(current_loss,[agent.weights])
    weights_as_np = agent.weights.numpy()
    responsible_weight = agent.weights[action]
    responsible_weight_dw = np.array(dW)[0][action]

    weights_as_np[action] = weights_as_np[action] - learning_rate*responsible_weight_dw

    agent.weights.assign(tf.Variable(weights_as_np))

1个回答

如果可能,请尝试仅使用tensorflow函数(.numpy()例如,将部分放在外面),并在函数@tf.function之上放置一个装饰器train()

的作用@tf.function是将整个函数转化为张量流操作。整个函数的执行速度将比普通 Python 函数快一个数量级。