此页面由 Cloud Translation API 翻译。
Switch to English

重播缓冲区

在TensorFlow.org上查看 在Google Colab中运行 在GitHub上查看源代码 下载笔记本

介绍

强化学习算法使用重播缓冲区来存储在环境中执行策略时的体验轨迹。在训练过程中,查询轨迹的子集(顺序子集或样本)的重播缓冲区,以“重播”代理的经验。

在本次合作中,我们探索了两种类型的重播缓冲区:python-backed和ten​​sorflow-backed,它们共享一个公共API。在以下各节中,我们将介绍API,每种缓冲区实现以及如何在数据收集培训期间使用它们。

建立

如果尚未安装tf-agent,请先安装。

pip install -q tf-agents
pip install -q gym
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
import numpy as np

from tf_agents import specs
from tf_agents.agents.dqn import dqn_agent
from tf_agents.drivers import dynamic_step_driver
from tf_agents.environments import suite_gym
from tf_agents.environments import tf_py_environment
from tf_agents.networks import q_network
from tf_agents.replay_buffers import py_uniform_replay_buffer
from tf_agents.replay_buffers import tf_uniform_replay_buffer
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import time_step

tf.compat.v1.enable_v2_behavior()

重播缓冲区API

重播缓冲区类具有以下定义和方法:

class ReplayBuffer(tf.Module):
  """Abstract base class for TF-Agents replay buffer."""

  def __init__(self, data_spec, capacity):
    """Initializes the replay buffer.

    Args:
      data_spec: A spec or a list/tuple/nest of specs describing
        a single item that can be stored in this buffer
      capacity: number of elements that the replay buffer can hold.
    """

  @property
  def data_spec(self):
    """Returns the spec for items in the replay buffer."""

  @property
  def capacity(self):
    """Returns the capacity of the replay buffer."""

  def add_batch(self, items):
    """Adds a batch of items to the replay buffer."""

  def get_next(self,
               sample_batch_size=None,
               num_steps=None,
               time_stacked=True):
    """Returns an item or batch of items from the buffer."""

  def as_dataset(self,
                 sample_batch_size=None,
                 num_steps=None,
                 num_parallel_calls=None):
    """Creates and returns a dataset that returns entries from the buffer."""


  def gather_all(self):
    """Returns all the items in buffer."""
    return self._gather_all()

  def clear(self):
    """Resets the contents of replay buffer"""

请注意,在初始化重播缓冲区对象时,它需要将存储的元素的data_spec 。此规范对应于将添加到缓冲区的轨迹元素的TensorSpec 。通常通过查看代理的agent.collect_data_spec来获取此规范,该代理定义了培训时代理期望的形状,类型和结构(稍后会详细介绍)

TFUniformReplayBuffer

TFUniformReplayBuffer是TF-Agent中最常用的重播缓冲区,因此我们将在本教程中使用它。在TFUniformReplayBuffer ,后备缓冲区存储由tensorflow变量完成,因此是计算图的一部分。

缓冲区存储元素批次,每个批次段具有最大容量max_length元素。因此,总缓冲区容量为batch_size x max_length元素。缓冲区中存储的元素必须全部具有匹配的数据规范。当将重放缓冲区用于数据收集时,该规范就是代理的收集数据规范。

创建缓冲区:

要创建TFUniformReplayBuffer我们传入:

  1. 缓冲区将存储的数据元素的规范
  2. 与缓冲区的batch size相对应的批量大小
  3. 每个批处理段的max_length元素max_length

这是一个使用示例数据规范( batch_size 32和max_length 1000)创建TFUniformReplayBuffer的示例。

data_spec =  (
        tf.TensorSpec([3], tf.float32, 'action'),
        (
            tf.TensorSpec([5], tf.float32, 'lidar'),
            tf.TensorSpec([3, 2], tf.float32, 'camera')
        )
)

batch_size = 32
max_length = 1000

replay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer(
    data_spec,
    batch_size=batch_size,
    max_length=max_length)

写入缓冲区:

要将元素添加到重播缓冲区,我们使用add_batch(items)方法,其中items是张量的列表/元组/嵌套的张量,表示要添加到缓冲区的一批商品。 items每个元素都必须具有等于batch_size的外部尺寸,并且其余尺寸必须遵守该项目的数据规范(与传递给重放缓冲区构造函数的数据规范相同)。

这是添加一批物品的示例

action = tf.constant(1 * np.ones(
    data_spec[0].shape.as_list(), dtype=np.float32))
lidar = tf.constant(
    2 * np.ones(data_spec[1][0].shape.as_list(), dtype=np.float32))
camera = tf.constant(
    3 * np.ones(data_spec[1][1].shape.as_list(), dtype=np.float32))
  
values = (action, (lidar, camera))
values_batched = tf.nest.map_structure(lambda t: tf.stack([t] * batch_size),
                                       values)
  
replay_buffer.add_batch(values_batched)

从缓冲区读取

有三种方法可以从TFUniformReplayBuffer读取数据:

  1. get_next() -从缓冲区返回一个样本。可以通过此方法的参数指定样本的批次大小和返回的时间步数。
  2. as_dataset() -将重播缓冲区作为tf.data.Dataset返回。然后可以创建一个数据集迭代器,并迭代缓冲区中各项的样本。
  3. gather_all() -以形状为[batch, time, data_spec]的张量返回缓冲区中的所有项目

下面是如何使用这些方法从重播缓冲区中进行读取的示例:

# add more items to the buffer before reading
for _ in range(5):
  replay_buffer.add_batch(values_batched)

# Get one sample from the replay buffer with batch size 10 and 1 timestep:

sample = replay_buffer.get_next(sample_batch_size=10, num_steps=1)

# Convert the replay buffer to a tf.data.Dataset and iterate through it
dataset = replay_buffer.as_dataset(
    sample_batch_size=4,
    num_steps=2)

iterator = iter(dataset)
print("Iterator trajectories:")
trajectories = []
for _ in range(3):
  t, _ = next(iterator)
  trajectories.append(t)
  
print(tf.nest.map_structure(lambda t: t.shape, trajectories))

# Read all elements in the replay buffer:
trajectories = replay_buffer.gather_all()

print("Trajectories from gather all:")
print(tf.nest.map_structure(lambda t: t.shape, trajectories))

WARNING:tensorflow:From <ipython-input-6-1f9907631cb9>:7: ReplayBuffer.get_next (from tf_agents.replay_buffers.replay_buffer) is deprecated and will be removed in a future version.
Instructions for updating:
Use `as_dataset(..., single_deterministic_pass=False) instead.
Iterator trajectories:
[(TensorShape([4, 2, 3]), (TensorShape([4, 2, 5]), TensorShape([4, 2, 3, 2]))), (TensorShape([4, 2, 3]), (TensorShape([4, 2, 5]), TensorShape([4, 2, 3, 2]))), (TensorShape([4, 2, 3]), (TensorShape([4, 2, 5]), TensorShape([4, 2, 3, 2])))]
WARNING:tensorflow:From <ipython-input-6-1f9907631cb9>:24: ReplayBuffer.gather_all (from tf_agents.replay_buffers.replay_buffer) is deprecated and will be removed in a future version.
Instructions for updating:
Use `as_dataset(..., single_deterministic_pass=True)` instead.
Trajectories from gather all:
(TensorShape([32, 6, 3]), (TensorShape([32, 6, 5]), TensorShape([32, 6, 3, 2])))

PyUniformReplayBuffer

PyUniformReplayBuffer具有相同的functionaly作为TFUniformReplayBuffer但不是TF变量,它的数据存储在numpy的阵列。该缓冲区可用于图形外数据收集。将备份存储空间设置为numpy可能会使某些应用程序更容易在不使用Tensorflow变量的情况下进行数据操作(例如为更新优先级建立索引)。但是,此实现不会具有使用Tensorflow进行图形优化的好处。

以下是从代理的策略轨迹规范实例化PyUniformReplayBuffer的示例:

replay_buffer_capacity = 1000*32 # same capacity as the TFUniformReplayBuffer

py_replay_buffer = py_uniform_replay_buffer.PyUniformReplayBuffer(
    capacity=replay_buffer_capacity,
    data_spec=tensor_spec.to_nest_array_spec(data_spec))

训练期间使用重播缓冲区

现在,我们知道了如何创建重播缓冲区,向其中写入项目并从中读取内容,我们可以在训练代理程序时使用它来存储轨迹。

数据采集

首先,让我们看一下如何在数据收集过程中使用重放缓冲区。

在TF-Agent中,我们使用Driver (有关更多详细信息,请参见驱动程序教程)来收集环境中的经验。要使用Driver ,我们指定一个Observer ,它是Driver在收到轨迹时执行的功能。

因此,要将轨迹元素添加到重播缓冲区中,我们添加了一个调用add_batch(items)的观察者,以在重播缓冲区中添加(批量)项。

下面是使用TFUniformReplayBuffer的示例。我们首先创建一个环境,一个网络和一个代理。然后,我们创建一个TFUniformReplayBuffer 。请注意,重播缓冲区中的轨迹元素的规格与代理的收集数据规格相同。然后,将其add_batch方法设置为驾驶员的观察者,该驾驶员将在我们的培训期间收集数据:

env = suite_gym.load('CartPole-v0')
tf_env = tf_py_environment.TFPyEnvironment(env)

q_net = q_network.QNetwork(
    tf_env.time_step_spec().observation,
    tf_env.action_spec(),
    fc_layer_params=(100,))

agent = dqn_agent.DqnAgent(
    tf_env.time_step_spec(),
    tf_env.action_spec(),
    q_network=q_net,
    optimizer=tf.compat.v1.train.AdamOptimizer(0.001))

replay_buffer_capacity = 1000

replay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer(
    agent.collect_data_spec,
    batch_size=tf_env.batch_size,
    max_length=replay_buffer_capacity)

# Add an observer that adds to the replay buffer:
replay_observer = [replay_buffer.add_batch]

collect_steps_per_iteration = 10
collect_op = dynamic_step_driver.DynamicStepDriver(
  tf_env,
  agent.collect_policy,
  observers=replay_observer,
  num_steps=collect_steps_per_iteration).run()
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tf_agents/drivers/dynamic_step_driver.py:203: calling while_loop_v2 (from tensorflow.python.ops.control_flow_ops) with back_prop=False is deprecated and will be removed in a future version.
Instructions for updating:
back_prop=False is deprecated. Consider using tf.stop_gradient instead.
Instead of:
results = tf.while_loop(c, b, vars, back_prop=False)
Use:
results = tf.nest.map_structure(tf.stop_gradient, tf.while_loop(c, b, vars))

读取火车步骤的数据

在将轨迹元素添加到重播缓冲区后,我们可以从重播缓冲区中读取一批轨迹,以用作训练步骤的输入数据。

这是一个如何在训练循环中从重播缓冲区训练轨迹的示例:

# Read the replay buffer as a Dataset,
# read batches of 4 elements, each with 2 timesteps:
dataset = replay_buffer.as_dataset(
    sample_batch_size=4,
    num_steps=2)

iterator = iter(dataset)

num_train_steps = 10

for _ in range(num_train_steps):
  trajectories, _ = next(iterator)
  loss = agent.train(experience=trajectories)

WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/util/dispatch.py:201: calling foldr_v2 (from tensorflow.python.ops.functional_ops) with back_prop=False is deprecated and will be removed in a future version.
Instructions for updating:
back_prop=False is deprecated. Consider using tf.stop_gradient instead.
Instead of:
results = tf.foldr(fn, elems, back_prop=False)
Use:
results = tf.nest.map_structure(tf.stop_gradient, tf.foldr(fn, elems))