快捷方式

make_tensordict

class tensordict.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, auto_batch_size: Optional[bool] = None, **kwargs: Tensor)

从关键字参数或输入字典返回一个创建的 TensorDict。

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

此函数还可以处理嵌套字典,或者用于确定嵌套 tensordict 的批次大小。

参数:
  • input_dict (dictionary, optional) – 用作数据源的字典(兼容嵌套键)。

  • **kwargs (TensorDicttorch.Tensor) – 作为数据源的关键字参数(与嵌套键不兼容)。

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

  • device (torch.devicecompatible type, optional) – TensorDict 的设备。

  • auto_batch_size (bool, optional) – 如果为 True,则会自动计算批次大小。默认为 False

示例

>>> 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 开发者文档

查看文档

教程

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

查看教程

资源

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

查看资源