快捷方式

tensordict.nn.make_tensordict

tensordict.nn.make_tensordict(input_dict: Optional[dict[str, torch.Tensor]] = None, batch_size: Optional[Union[Sequence[int], Size, int]] = None, device: Optional[Union[device, str, int]] = None, **kwargs: Tensor) TensorDict

傳回從關鍵字引數或輸入字典建立的 TensorDict。

如果未指定 batch_size,則傳回可能的最大批次大小。

此函數也適用於巢狀字典,或可用於判斷巢狀 tensordict 的批次大小。

參數:
  • input_dict (dictionary, optional) – 用作資料來源的字典(相容於巢狀鍵)。

  • **kwargs (TensorDicttorch.Tensor) – 作為資料來源的關鍵字引數(與巢狀鍵不相容)。

  • batch_size (iterable of int, optional) – tensordict 的批次大小。

  • device (torch.device相容類型, optional) – TensorDict 的裝置。

範例

>>> input_dict = {"a": torch.randn(3, 4), "b": torch.randn(3)}
>>> print(make_tensordict(input_dict))
TensorDict(
    fields={
        a: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False),
        b: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False)},
    batch_size=torch.Size([3]),
    device=None,
    is_shared=False)
>>> # alternatively
>>> td = make_tensordict(**input_dict)
>>> # nested dict: the nested TensorDict can have a different batch-size
>>> # as long as its leading dims match.
>>> input_dict = {"a": torch.randn(3), "b": {"c": torch.randn(3, 4)}}
>>> print(make_tensordict(input_dict))
TensorDict(
    fields={
        a: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False),
        b: TensorDict(
            fields={
                c: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False)},
            batch_size=torch.Size([3, 4]),
            device=None,
            is_shared=False)},
    batch_size=torch.Size([3]),
    device=None,
    is_shared=False)
>>> # we can also use this to work out the batch sie of a tensordict
>>> input_td = TensorDict({"a": torch.randn(3), "b": {"c": torch.randn(3, 4)}}, [])
>>> print(make_tensordict(input_td))
TensorDict(
    fields={
        a: Tensor(shape=torch.Size([3]), device=cpu, dtype=torch.float32, is_shared=False),
        b: TensorDict(
            fields={
                c: Tensor(shape=torch.Size([3, 4]), device=cpu, dtype=torch.float32, is_shared=False)},
            batch_size=torch.Size([3, 4]),
            device=None,
            is_shared=False)},
    batch_size=torch.Size([3]),
    device=None,
    is_shared=False)

文件

取得 PyTorch 的完整開發者文件

檢視文件

教學

取得適合初學者和進階開發者的深入教學課程

檢視教學課程

資源

尋找開發資源並獲得問題解答

檢視資源