快捷方式

TargetReturn

class torchrl.envs.transforms.TargetReturn(target_return: float, mode: str = 'reduce', in_keys: Sequence[NestedKey] | None = None, out_keys: Sequence[NestedKey] | None = None, reset_key: NestedKey | None = None)[源代码]

为代理在环境中达成的目标设定一个目标回报。

在目标条件强化学习中,TargetReturn 定义为从当前状态到目标状态或回合结束时预期的累积奖励。它作为策略的输入来指导其行为。对于训练好的策略,通常会选择环境中最大的回报作为目标回报。但是,由于它用作策略模块的输入,因此应相应地进行缩放。通过 TargetReturn 变换,可以更新 tensordict 以包含用户指定的 target_returnmode 参数可用于指定目标回报是否通过在每一步减去获得的奖励来更新,还是保持不变。

参数:
  • target_return (float) – 代理需要达到的目标回报。

  • mode (str) – 用于更新目标回报的模式。可以是 “reduce” 或 “constant”。默认值:“reduce”。

  • in_keys (NestedKey 序列, 可选) – 指向奖励条目的键。默认为父环境的奖励键。

  • out_keys (NestedKey 序列, 可选) – 指向目标键的键。默认为 in_keys 的副本,其中最后一个元素已被 "target_return" 替换,如果这些键不唯一,则会引发异常。

  • reset_key (NestedKey, 可选) – 用作部分重置指示符的重置键。必须是唯一的。如果未提供,则默认为父环境的唯一重置键(如果只有一个),否则会引发异常。

示例

>>> from torchrl.envs import GymEnv
>>> env = TransformedEnv(
...     GymEnv("CartPole-v1"),
...     TargetReturn(10.0, mode="reduce"))
>>> env.set_seed(0)
>>> torch.manual_seed(0)
>>> env.rollout(20)['target_return'].squeeze()
tensor([10.,  9.,  8.,  7.,  6.,  5.,  4.,  3.,  2.,  1.,  0., -1., -2., -3.])
forward(tensordict: TensorDictBase) TensorDictBase[源代码]

读取输入 tensordict,并对选定的键应用转换。

默认情况下,此方法

  • 直接调用 _apply_transform()

  • 不调用 _step()_call()

此方法在任何时候都不会在 env.step 中调用。但是,它会在 sample() 中被调用。

注意

forward 使用 dispatch 也支持使用常规关键字参数将参数名称转换为键。

示例

>>> class TransformThatMeasuresBytes(Transform):
...     '''Measures the number of bytes in the tensordict, and writes it under `"bytes"`.'''
...     def __init__(self):
...         super().__init__(in_keys=[], out_keys=["bytes"])
...
...     def forward(self, tensordict: TensorDictBase) -> TensorDictBase:
...         bytes_in_td = tensordict.bytes()
...         tensordict["bytes"] = bytes
...         return tensordict
>>> t = TransformThatMeasuresBytes()
>>> env = env.append_transform(t) # works within envs
>>> t(TensorDict(a=0))  # Works offline too.
transform_input_spec(input_spec: TensorSpec) TensorSpec[源代码]

转换输入规范,使结果规范与转换映射匹配。

参数:

input_spec (TensorSpec) – 转换前的规范

返回:

转换后的预期规范

transform_observation_spec(observation_spec: TensorSpec) TensorSpec[源代码]

转换观察规范,使结果规范与转换映射匹配。

参数:

observation_spec (TensorSpec) – 转换前的规范

返回:

转换后的预期规范

文档

访问全面的 PyTorch 开发者文档

查看文档

教程

为初学者和高级开发者提供深入的教程

查看教程

资源

查找开发资源并让您的问题得到解答

查看资源