NonTensor¶
- class torchrl.data.NonTensor(shape: torch.Size | int = torch.Size([1]), device: DEVICE_TYPING | None = None, dtype: torch.dtype | None = None, example_data: Any = None, batched: bool | None = None, feature_dims: int | None = None, **kwargs)[源代码]¶
用于非张量数据的规范。
The NonTensor class is designed to handle specifications for data that do not conform to standard tensor structures. It maintains attributes such as shape, and device similar to the NonTensorData class. The dtype is optional and should in practice be left to None in most cases. Methods like rand, zero, and one will return a NonTensorData object with a None data value.
警告
The default shape of NonTensor is (1,).
- 参数:
shape (Union[torch.Size, int], optional) – 非张量数据的形状。默认为 (1,)。
device (Optional[DEVICE_TYPING], optional) – 存储数据的设备。默认为 None。
dtype (torch.dtype | None, optional) – 非张量数据的类型。默认为 None。
example_data (Any, optional) – 该规范所代表数据的示例。此示例用作通过 rand, zero, 和 one 方法生成新数据的模板。
batched (bool, optional) – 指示数据是否已批处理。如果为 True,则 rand, zero, 和 one 方法将生成具有额外批次维度的数据,并在该维度上堆叠 example_data 的副本。默认为 False。与 feature_dims 互斥。
feature_dims (int, optional) – 特征的维度数。特征维度是非批次维度的尾随维度。每个特征维度都包含在一个 NonTensorData 对象中,而这些对象在批次维度上进行堆叠。与 batched 互斥。默认为 None(如果 batched=False 则为所有,如果 batched=True 则为无)。
**kwargs – 传递给父类的其他关键字参数。
另请参阅
Choice
,它允许在调用 rand 时在不同规范之间随机选择。示例
>>> from torchrl.data import NonTensor >>> spec = NonTensor(example_data="a string", batched=False, shape=(3,)) >>> spec.rand() NonTensorData(data=a string, batch_size=torch.Size([3]), device=None) >>> spec = NonTensor(example_data="a string", batched=True, shape=(3,)) >>> spec.rand() NonTensorStack( ['a string', 'a string', 'a string'], batch_size=torch.Size([3]), device=None)
- assert_is_in(value: Tensor) None ¶
断言一个张量是否属于该区域(box),否则抛出异常。
- 参数:
value (torch.Tensor) – 要检查的值。
- contains(item: torch.Tensor | TensorDictBase) bool ¶
If the value
val
could have been generated by theTensorSpec
, returnsTrue
, otherwiseFalse
.See
is_in()
for more information.
- cpu()¶
将 TensorSpec 转换为“cpu”设备。
- cuda(device=None)¶
将 TensorSpec 转换为“cuda”设备。
- property device: device¶
规格的设备。
Only
Composite
specs can have aNone
device. All leaves must have a non-null device.
- encode(val: np.ndarray | list | torch.Tensor | TensorDictBase, *, ignore_device: bool = False) torch.Tensor | TensorDictBase ¶
使用指定的规格对值进行编码,并返回相应的张量。
此方法用于返回易于映射到 TorchRL 所需域的值(例如 numpy 数组)的环境。如果值已经是张量,则规格不会更改其值,而是按原样返回。
- 参数:
val (np.ndarray 或 torch.Tensor) – 要编码为张量的值。
- 关键字参数:
ignore_device (bool, optional) – 如果为
True
,则忽略规范设备。这用于在调用TensorDict(..., device="cuda")
期间将张量强制转换分组,这样更快速。- 返回:
符合所需张量规格的 torch.Tensor。
- enumerate(use_mask: bool = False) Any [源代码]¶
返回可以从 TensorSpec 获得的所有样本。
样本将沿第一个维度堆叠。
此方法仅为离散规格实现。
- 参数:
use_mask (bool, optional) – 如果为
True
且规范具有掩码,则排除被掩码的样本。默认为False
。
- erase_memoize_cache() None ¶
清除用于缓存 encode 执行的缓存。
另请参阅
- expand(*shape)[源代码]¶
返回一个具有扩展形状的新 Spec。
- 参数:
*shape (tuple or iterable of int) – Spec 的新形状。必须可广播到当前形状:其长度至少应等于当前形状的长度,并且其最后一个值也必须兼容;即,它们仅在当前维度为单例时才能与当前维度不同。
- classmethod implements_for_spec(torch_function: Callable) Callable ¶
为 TensorSpec 注册一个 torch 函数覆盖。
- index(index: INDEX_TYPING, tensor_to_index: torch.Tensor | TensorDictBase) torch.Tensor | TensorDictBase [源代码]¶
索引输入张量。
此方法用于索引编码一个或多个分类变量的规范(例如,
OneHot
或Categorical
),以便在不对索引的实际表示进行关心的情况下对张量进行索引。- 参数:
index (int, torch.Tensor, slice or list) – 张量的索引
tensor_to_index – 要索引的张量
- 返回:
被索引的张量
- 示例
>>> from torchrl.data import OneHot >>> import torch >>> >>> one_hot = OneHot(n=100) >>> categ = one_hot.to_categorical_spec() >>> idx_one_hot = torch.zeros((100,), dtype=torch.bool) >>> idx_one_hot[50] = 1 >>> print(one_hot.index(idx_one_hot, torch.arange(100))) tensor(50) >>> idx_categ = one_hot.to_categorical(idx_one_hot) >>> print(categ.index(idx_categ, torch.arange(100))) tensor(50)
- is_in(val: Any) bool [源代码]¶
If the value
val
could have been generated by theTensorSpec
, returnsTrue
, otherwiseFalse
.More precisely, the
is_in
methods checks that the valueval
is within the limits defined by thespace
attribute (the box), and that thedtype
,device
,shape
potentially other metadata match those of the spec. If any of these checks fails, theis_in
method will returnFalse
.- 参数:
val (torch.Tensor) – 要检查的值。
- 返回:
布尔值,指示值是否属于 TensorSpec 区域。
- make_neg_dim(dim: int) T ¶
将特定维度转换为
-1
。
- memoize_encode(mode: bool = True) None ¶
创建 encode 方法的缓存可调用序列,以加快其执行速度。
这应该只在输入类型、形状等在给定规格的调用之间预期一致时使用。
- 参数:
mode (bool, optional) – 是否使用缓存。默认为 True。
另请参阅
缓存可以通过
erase_memoize_cache()
擦除。
- property ndim: int¶
规格形状的维数。
相当于
len(spec.shape)
。
- ndimension() int ¶
规格形状的维数。
相当于
len(spec.shape)
。
- one(shape=None)[源代码]¶
返回盒中的一个填充一的张量。
注意
Even though there is no guarantee that
1
belongs to the spec domain, this method will not raise an exception when this condition is violated. The primary use case ofone
is to generate empty data buffers, not meaningful data.- 参数:
shape (torch.Size) – 一维张量的形状
- 返回:
在 TensorSpec 区域中采样的填充一的张量。
- ones(shape: torch.Size = None) torch.Tensor | TensorDictBase ¶
Proxy to
one()
.
- project(val: torch.Tensor | TensorDictBase) torch.Tensor | TensorDictBase ¶
如果输入张量不在 TensorSpec 区域内,则根据定义的启发式方法将其映射回该区域。
- 参数:
val (torch.Tensor) – 要映射到区域的张量。
- 返回:
属于 TensorSpec 区域的 torch.Tensor。
- rand(shape=None)[源代码]¶
返回规格定义的区域中的随机张量。
采样将在区域内均匀进行,除非区域无界,在这种情况下将绘制正态值。
- 参数:
shape (torch.Size) – 随机张量的形状
- 返回:
在 TensorSpec 区域中采样的随机张量。
- sample(shape: torch.Size = None) torch.Tensor | TensorDictBase ¶
返回规格定义的区域中的随机张量。
请参阅
rand()
获取详细信息。
- squeeze(dim: int | None = None) NonTensor [源代码]¶
返回一个新 Spec,其中所有大小为
1
的维度都已删除。当给定
dim
时,仅在该维度上执行挤压操作。- 参数:
dim (int 或 None) – 应用挤压操作的维度
- to(dest: torch.dtype | DEVICE_TYPING) NonTensor [源代码]¶
将 TensorSpec 转换为设备或 dtype。
如果未进行更改,则返回相同的规格。
- to_numpy(val: torch.Tensor | TensorDictBase, safe: bool | None = None) np.ndarray | dict [源代码]¶
返回输入张量的
np.ndarray
对应项。This is intended to be the inverse operation of
encode()
.- 参数:
val (torch.Tensor) – 要转换为 numpy 的张量。
safe (bool) – boolean value indicating whether a check should be performed on the value against the domain of the spec. Defaults to the value of the
CHECK_SPEC_ENCODE
environment variable.
- 返回:
一个 np.ndarray。
- type_check(value: Tensor, key: Optional[NestedKey] = None) None ¶
Checks the input value
dtype
against theTensorSpec
dtype
and raises an exception if they don’t match.- 参数:
value (torch.Tensor) – 必须检查其 dtype 的张量。
key (str, optional) – 如果 TensorSpec 具有键,则将检查值 dtype 是否与指定键指向的规格匹配。
- unflatten(dim: int, sizes: tuple[int]) T ¶
解展一个
TensorSpec
。有关此方法的更多信息,请参阅
unflatten()
。
- unsqueeze(dim: int) NonTensor [源代码]¶
返回一个新 Spec,其中在
dim
指定的位置增加了一个单例维度。- 参数:
dim (int 或 None) – 应用 unsqueeze 操作的维度。
- zero(shape=None)[源代码]¶
返回盒中的零填充张量。
注意
Even though there is no guarantee that
0
belongs to the spec domain, this method will not raise an exception when this condition is violated. The primary use case ofzero
is to generate empty data buffers, not meaningful data.- 参数:
shape (torch.Size) – 零张量的形状
- 返回:
在 TensorSpec 框中采样的零填充张量。
- zeros(shape: torch.Size = None) torch.Tensor | TensorDictBase ¶
作为
zero()
的代理。