快捷方式

SelectTransform

class torchrl.envs.transforms.SelectTransform(*selected_keys: NestedKey, keep_rewards: bool = True, keep_dones: bool = True)[源代码]

从 input tensordict 中选择键。

一般来说,应优先使用 ExcludeTransform:此变换也

选择“action”(或 input_spec 中的其他键)、“done”和“reward”键,但其他键也可能是必需的。

参数:

*selected_keys (iterable of NestedKey) – 要选择的键的名称。如果键不存在,则会被忽略。

关键字参数:
  • keep_rewards (bool, optional) – 如果为 False,则必须提供 reward 键才能保留。默认为 True

  • keep_dones (bool, optional) – 如果为 False,则必须提供 done 键才能保留。默认为 True

示例

>>> import gymnasium
>>> from torchrl.envs import GymWrapper
>>> env = TransformedEnv(
...     GymWrapper(gymnasium.make("Pendulum-v1")),
...     SelectTransform("observation", "reward", "done", keep_dones=False), # we leave done behind
... )
>>> env.rollout(3)  # the truncated key is now absent
TensorDict(
    fields={
        action: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.float32, is_shared=False),
        done: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
        next: TensorDict(
            fields={
                done: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
                observation: Tensor(shape=torch.Size([3, 3]), device=cpu, dtype=torch.float32, is_shared=False),
                reward: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.float32, is_shared=False)},
            batch_size=torch.Size([3]),
            device=cpu,
            is_shared=False),
        observation: Tensor(shape=torch.Size([3, 3]), device=cpu, dtype=torch.float32, is_shared=False)},
    batch_size=torch.Size([3]),
    device=cpu,
    is_shared=False)
forward(next_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_output_spec(output_spec: Composite) Composite[源代码]

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

此方法通常应保持不变。更改应使用 transform_observation_spec()transform_reward_spec()transform_full_done_spec() 来实现。 :param output_spec: 变换前的 spec :type output_spec: TensorSpec

返回:

转换后的预期规范

文档

访问全面的 PyTorch 开发者文档

查看文档

教程

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

查看教程

资源

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

查看资源