from_dict¶
- class tensordict.from_dict(input_dict, batch_size=None, device=None, batch_dims=None, names=None)¶
返回从字典或另一个
TensorDict
创建的 TensorDict。如果未指定
batch_size
,则返回最大可能的批大小。此函数也适用于嵌套字典,或可用于确定嵌套 tensordict 的批大小。
- 参数:
input_dict (dictionary, optional) – 用作数据源的字典(兼容嵌套键)。
batch_size (iterable of int, optional) – tensordict 的批大小。
device (torch.device 或 compatible type, optional) – TensorDict 的设备。
batch_dims (int, optional) –
batch_dims
(即要考虑batch_size
的前导维度数)。与batch_size
互斥。请注意,这是 tensordict 的 __最大__ 批维度数,允许较小的数字。names (list of str, optional) – tensordict 的维度名称。
示例
>>> input_dict = {"a": torch.randn(3, 4), "b": torch.randn(3)} >>> print(from_dict(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) >>> # 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(from_dict(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( from_dict(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)