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 以包含使用者指定的目標回報。可以使用mode引數來指定目標回報是在每一步透過減去每一步獲得的獎勵來更新,還是保持不變。- 引數:
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) – 轉換前的規範
- 返回:
轉換後的預期規範