快捷方式

SelectTransform

class torchrl.envs.transforms.SelectTransform(*selected_keys: NestedKey, keep_rewards: bool = True, keep_dones: bool = True)[原始碼]

從輸入 tensordict 中選擇鍵。

通常,建議使用 ExcludeTransform:此轉換也

選擇“action”(或 input_spec 中的其他鍵)、“done”和“reward”鍵,但其他鍵也可能必需。

引數:

*selected_keys (iterable of NestedKey) – 要選擇的鍵的名稱。如果鍵不存在,則會簡單地忽略。

關鍵字引數:
  • keep_rewards (bool, optional) – 如果為 False,則必須提供獎勵鍵(如果要保留)。預設為 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 開發者文件

檢視文件

教程

為初學者和高階開發者提供深入的教程

檢視教程

資源

查詢開發資源並讓您的問題得到解答

檢視資源