快捷方式

OpenMLExperienceReplay

class torchrl.data.datasets.OpenMLExperienceReplay(name: str, batch_size: int, root: Path | None = None, sampler: Sampler | None = None, writer: Writer | None = None, collate_fn: Callable | None = None, pin_memory: bool = False, prefetch: int | None = None, transform: Transform | None = None)[原始碼]

OpenML 資料經驗回放。

此類提供公共資料集的便捷入口。參見“Dua, D. and Graff, C. (2017) UCI Machine Learning Repository。 http://archive.ics.uci.edu/ml

資料格式遵循 TED 約定

資料透過 scikit-learn 訪問。在檢索資料之前,請確保已安裝 sklearn 和 pandas。

$ pip install scikit-learn pandas -U
引數:
  • name (str) – 支援以下資料集: "adult_num""adult_onehot""mushroom_num""mushroom_onehot""covertype""shuttle""magic"

  • batch_size (int) – 取樣時使用的批次大小。

  • sampler (Sampler, optional) – 要使用的取樣器。如果未提供,將使用預設的 RandomSampler()。

  • writer (Writer, optional) – 要使用的寫入器。如果未提供,將使用預設的 ImmutableDatasetWriter

  • collate_fn (callable, 可選) – 將樣本列表合併以形成 Tensor(s)/輸出的 mini-batch。在從 map 風格的資料集進行批處理載入時使用。

  • pin_memory (bool) – 是否應對 rb 樣本呼叫 pin_memory()。

  • prefetch (int, 可選) – 使用多執行緒預取的下一個批次數。

  • transform (Transform, optional) – 呼叫 sample() 時要執行的轉換。要連結轉換,請使用 Compose 類。

add(data: TensorDictBase) int

將單個元素新增到重放緩衝區。

引數:

data (Any) – 要新增到重放緩衝區的資料

返回:

資料在重放緩衝區中的索引。

append_transform(transform: Transform, *, invert: bool = False) ReplayBuffer

將變換附加到末尾。

呼叫 sample 時按順序應用變換。

引數:

transform (Transform) – 要附加的變換

關鍵字引數:

invert (bool, optional) – 如果為 True,則轉換將被反轉(寫入時呼叫正向呼叫,讀取時呼叫反向呼叫)。預設為 False

示例

>>> rb = ReplayBuffer(storage=LazyMemmapStorage(10), batch_size=4)
>>> data = TensorDict({"a": torch.zeros(10)}, [10])
>>> def t(data):
...     data += 1
...     return data
>>> rb.append_transform(t, invert=True)
>>> rb.extend(data)
>>> assert (data == 1).all()
classmethod as_remote(remote_config=None)

建立一個遠端 ray 類的例項。

引數:
  • cls (Python Class) – 要遠端例項化的類。

  • remote_config (dict) – 為該類保留的 CPU 核心數量。預設為 torchrl.collectors.distributed.ray.DEFAULT_REMOTE_CLASS_CONFIG

返回:

一個建立 ray 遠端類例項的函式。

property batch_size

重放緩衝區的批次大小。

可以透過在 sample() 方法中設定 batch_size 引數來覆蓋批次大小。

它定義了 sample() 返回的樣本數量以及 ReplayBuffer 迭代器產生的樣本數量。

abstract property data_path: Path

資料集路徑,包括分割。

abstract property data_path_root: Path

資料集根目錄路徑。

delete()

從磁碟刪除資料集儲存。

dump(*args, **kwargs)

Alias for dumps()

dumps(path)

將重放緩衝區儲存到指定路徑的磁碟上。

引數:

path (Pathstr) – 儲存重放緩衝區的路徑。

示例

>>> import tempfile
>>> import tqdm
>>> from torchrl.data import LazyMemmapStorage, TensorDictReplayBuffer
>>> from torchrl.data.replay_buffers.samplers import PrioritizedSampler, RandomSampler
>>> import torch
>>> from tensordict import TensorDict
>>> # Build and populate the replay buffer
>>> S = 1_000_000
>>> sampler = PrioritizedSampler(S, 1.1, 1.0)
>>> # sampler = RandomSampler()
>>> storage = LazyMemmapStorage(S)
>>> rb = TensorDictReplayBuffer(storage=storage, sampler=sampler)
>>>
>>> for _ in tqdm.tqdm(range(100)):
...     td = TensorDict({"obs": torch.randn(100, 3, 4), "next": {"obs": torch.randn(100, 3, 4)}, "td_error": torch.rand(100)}, [100])
...     rb.extend(td)
...     sample = rb.sample(32)
...     rb.update_tensordict_priority(sample)
>>> # save and load the buffer
>>> with tempfile.TemporaryDirectory() as tmpdir:
...     rb.dumps(tmpdir)
...
...     sampler = PrioritizedSampler(S, 1.1, 1.0)
...     # sampler = RandomSampler()
...     storage = LazyMemmapStorage(S)
...     rb_load = TensorDictReplayBuffer(storage=storage, sampler=sampler)
...     rb_load.loads(tmpdir)
...     assert len(rb) == len(rb_load)
empty(empty_write_count: bool = True)

清空重放緩衝區並將遊標重置為 0。

引數:

empty_write_count (bool, optional) – 是否清空 write_count 屬性。預設為 True

extend(tensordicts: TensorDictBase, *, update_priority: bool | None = None) torch.Tensor

使用資料批次擴充套件重放緩衝區。

引數:

tensordicts (TensorDictBase) – 用於擴充套件重放緩衝區的資料。

關鍵字引數:

update_priority (bool, optional) – 是否更新資料的優先順序。預設為 True。

返回:

已新增到重放緩衝區的資料的索引。

insert_transform(index: int, transform: Transform, *, invert: bool = False) ReplayBuffer

插入變換。

呼叫 sample 時按順序執行變換。

引數:
  • index (int) – 插入變換的位置。

  • transform (Transform) – 要附加的變換

關鍵字引數:

invert (bool, optional) – 如果為 True,則轉換將被反轉(寫入時呼叫正向呼叫,讀取時呼叫反向呼叫)。預設為 False

load(*args, **kwargs)

Alias for loads()

loads(path)

在給定路徑載入重放緩衝區狀態。

緩衝區應具有匹配的元件,並使用 dumps() 儲存。

引數:

path (Pathstr) – 重放緩衝區儲存的路徑。

有關更多資訊,請參閱 dumps()

next()

返回重放緩衝區的下一個項。

此方法用於在 __iter__ 不可用的情況下迭代重放緩衝區,例如 RayReplayBuffer

preprocess(fn: Callable[[TensorDictBase], TensorDictBase], dim: int = 0, num_workers: int | None = None, *, chunksize: int | None = None, num_chunks: int | None = None, pool: mp.Pool | None = None, generator: torch.Generator | None = None, max_tasks_per_child: int | None = None, worker_threads: int = 1, index_with_generator: bool = False, pbar: bool = False, mp_start_method: str | None = None, num_frames: int | None = None, dest: str | Path) TensorStorage

預處理資料集並返回一個包含格式化資料的新儲存。

資料轉換必須是單位化的(作用於資料集的單個樣本)。

Args 和 Keyword Args 會轉發給 map()

資料集之後可以使用 delete() 進行刪除。

關鍵字引數:
  • dest (path等價物) – 新資料集位置的路徑。

  • num_frames (int, 可選) – 如果提供,則僅轉換前 num_frames 幀。這對於除錯轉換很有用。

返回:將在 ReplayBuffer 例項中使用的新的儲存。

示例

>>> from torchrl.data.datasets import MinariExperienceReplay
>>>
>>> data = MinariExperienceReplay(
...     list(MinariExperienceReplay.available_datasets)[0],
...     batch_size=32
...     )
>>> print(data)
MinariExperienceReplay(
    storages=TensorStorage(TensorDict(
        fields={
            action: MemoryMappedTensor(shape=torch.Size([1000000, 8]), device=cpu, dtype=torch.float32, is_shared=True),
            episode: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.int64, is_shared=True),
            info: TensorDict(
                fields={
                    distance_from_origin: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                    forward_reward: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                    goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True),
                    qpos: MemoryMappedTensor(shape=torch.Size([1000000, 15]), device=cpu, dtype=torch.float64, is_shared=True),
                    qvel: MemoryMappedTensor(shape=torch.Size([1000000, 14]), device=cpu, dtype=torch.float64, is_shared=True),
                    reward_ctrl: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                    reward_forward: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                    reward_survive: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                    success: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.bool, is_shared=True),
                    x_position: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                    x_velocity: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                    y_position: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                    y_velocity: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True)},
                batch_size=torch.Size([1000000]),
                device=cpu,
                is_shared=False),
            next: TensorDict(
                fields={
                    done: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True),
                    info: TensorDict(
                        fields={
                            distance_from_origin: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                            forward_reward: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                            goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True),
                            qpos: MemoryMappedTensor(shape=torch.Size([1000000, 15]), device=cpu, dtype=torch.float64, is_shared=True),
                            qvel: MemoryMappedTensor(shape=torch.Size([1000000, 14]), device=cpu, dtype=torch.float64, is_shared=True),
                            reward_ctrl: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                            reward_forward: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                            reward_survive: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                            success: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.bool, is_shared=True),
                            x_position: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                            x_velocity: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                            y_position: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True),
                            y_velocity: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.float64, is_shared=True)},
                        batch_size=torch.Size([1000000]),
                        device=cpu,
                        is_shared=False),
                    observation: TensorDict(
                        fields={
                            achieved_goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True),
                            desired_goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True),
                            observation: MemoryMappedTensor(shape=torch.Size([1000000, 27]), device=cpu, dtype=torch.float64, is_shared=True)},
                        batch_size=torch.Size([1000000]),
                        device=cpu,
                        is_shared=False),
                    reward: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.float64, is_shared=True),
                    terminated: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True),
                    truncated: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True)},
                batch_size=torch.Size([1000000]),
                device=cpu,
                is_shared=False),
            observation: TensorDict(
                fields={
                    achieved_goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True),
                    desired_goal: MemoryMappedTensor(shape=torch.Size([1000000, 2]), device=cpu, dtype=torch.float64, is_shared=True),
                    observation: MemoryMappedTensor(shape=torch.Size([1000000, 27]), device=cpu, dtype=torch.float64, is_shared=True)},
                batch_size=torch.Size([1000000]),
                device=cpu,
                is_shared=False)},
        batch_size=torch.Size([1000000]),
        device=cpu,
        is_shared=False)),
    samplers=RandomSampler,
    writers=ImmutableDatasetWriter(),
batch_size=32,
transform=Compose(
),
collate_fn=<function _collate_id at 0x120e21dc0>)
>>> from torchrl.envs import CatTensors, Compose
>>> from tempfile import TemporaryDirectory
>>>
>>> cat_tensors = CatTensors(
...     in_keys=[("observation", "observation"), ("observation", "achieved_goal"),
...              ("observation", "desired_goal")],
...     out_key="obs"
...     )
>>> cat_next_tensors = CatTensors(
...     in_keys=[("next", "observation", "observation"),
...              ("next", "observation", "achieved_goal"),
...              ("next", "observation", "desired_goal")],
...     out_key=("next", "obs")
...     )
>>> t = Compose(cat_tensors, cat_next_tensors)
>>>
>>> def func(td):
...     td = td.select(
...         "action",
...         "episode",
...         ("next", "done"),
...         ("next", "observation"),
...         ("next", "reward"),
...         ("next", "terminated"),
...         ("next", "truncated"),
...         "observation"
...         )
...     td = t(td)
...     return td
>>> with TemporaryDirectory() as tmpdir:
...     new_storage = data.preprocess(func, num_workers=4, pbar=True, mp_start_method="fork", dest=tmpdir)
...     rb = ReplayBuffer(storage=new_storage)
...     print(rb)
ReplayBuffer(
    storage=TensorStorage(
        data=TensorDict(
            fields={
                action: MemoryMappedTensor(shape=torch.Size([1000000, 8]), device=cpu, dtype=torch.float32, is_shared=True),
                episode: MemoryMappedTensor(shape=torch.Size([1000000]), device=cpu, dtype=torch.int64, is_shared=True),
                next: TensorDict(
                    fields={
                        done: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True),
                        obs: MemoryMappedTensor(shape=torch.Size([1000000, 31]), device=cpu, dtype=torch.float64, is_shared=True),
                        observation: TensorDict(
                            fields={
                            },
                            batch_size=torch.Size([1000000]),
                            device=cpu,
                            is_shared=False),
                        reward: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.float64, is_shared=True),
                        terminated: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True),
                        truncated: MemoryMappedTensor(shape=torch.Size([1000000, 1]), device=cpu, dtype=torch.bool, is_shared=True)},
                    batch_size=torch.Size([1000000]),
                    device=cpu,
                    is_shared=False),
                obs: MemoryMappedTensor(shape=torch.Size([1000000, 31]), device=cpu, dtype=torch.float64, is_shared=True),
                observation: TensorDict(
                    fields={
                    },
                    batch_size=torch.Size([1000000]),
                    device=cpu,
                    is_shared=False)},
            batch_size=torch.Size([1000000]),
            device=cpu,
            is_shared=False),
        shape=torch.Size([1000000]),
        len=1000000,
        max_size=1000000),
    sampler=RandomSampler(),
    writer=RoundRobinWriter(cursor=0, full_storage=True),
    batch_size=None,
    collate_fn=<function _collate_id at 0x168406fc0>)
register_load_hook(hook: Callable[[Any], Any])

為儲存註冊載入鉤子。

注意

鉤子目前不會在儲存重放緩衝區時序列化:每次建立緩衝區時都必須手動重新初始化它們。

register_save_hook(hook: Callable[[Any], Any])

為儲存註冊儲存鉤子。

注意

鉤子目前不會在儲存重放緩衝區時序列化:每次建立緩衝區時都必須手動重新初始化它們。

sample(batch_size: int | None = None, return_info: bool = False, include_info: bool | None = None) TensorDictBase

從重放緩衝區中取樣資料批次。

使用 Sampler 取樣索引,並從 Storage 中檢索它們。

引數:
  • batch_size (int, optional) – 要收集的資料的大小。如果未提供,此方法將取樣由取樣器指示的批次大小。

  • return_info (bool) – 是否返回資訊。如果為 True,則結果為元組 (data, info)。如果為 False,則結果為資料。

返回:

一個包含在重放緩衝區中選擇的資料批次的 tensordict。如果 return_info 標誌設定為 True,則包含此 tensordict 和資訊的元組。

property sampler: Sampler

重放緩衝區的取樣器。

取樣器必須是 Sampler 的例項。

save(*args, **kwargs)

Alias for dumps()

set_sampler(sampler: Sampler)

在重放緩衝區中設定新的取樣器並返回之前的取樣器。

set_storage(storage: Storage, collate_fn: Callable | None = None)

在重放緩衝區中設定新的儲存並返回之前的儲存。

引數:
  • storage (Storage) – 緩衝區的新的儲存。

  • collate_fn (callable, optional) – 如果提供,collate_fn 將設定為此值。否則,它將被重置為預設值。

set_writer(writer: Writer)

在重放緩衝區中設定新的寫入器並返回之前的寫入器。

property storage: Storage

重放緩衝區的儲存。

儲存器必須是 Storage 的例項。

property write_count: int

透過 add 和 extend 寫入緩衝區的總項數。

property writer: Writer

重放緩衝區的寫入器。

寫入器必須是 Writer 的例項。

文件

訪問全面的 PyTorch 開發者文件

檢視文件

教程

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

檢視教程

資源

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

檢視資源