快捷方式

Bounded

class torchrl.data.Bounded(*args, **kwargs)[source]

一种有界的张量规范。

Bounded 规范本身不会直接出现,而是会根据其数据类型(dtype)被子类化为 BoundedContinuousBoundedDiscrete(浮点类型的数据类型将产生 BoundedContinuous 实例,所有其他类型将产生 BoundedDiscrete 实例)。

参数:
  • low (np.ndarray, torch.Tensornumber) – 盒子的下界。

  • high (np.ndarray, torch.Tensornumber) – 盒子的上界。

  • shape (torch.Size) – Bounded 规范的形状。必须指定形状。输入 lowhighshape 必须可广播 (broadcastable)。

  • device (str, inttorch.device, optional) – 张量的设备。

  • dtype (strtorch.dtype, optional) – 张量的数据类型(dtype)。

  • domain (str) – “continuous”“discrete”。可用于覆盖自动类型分配。

示例

>>> spec = Bounded(low=-1, high=1, shape=(), dtype=torch.float)
>>> spec
BoundedContinuous(
    shape=torch.Size([]),
    space=ContinuousBox(
        low=Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, contiguous=True),
        high=Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, contiguous=True)),
    device=cpu,
    dtype=torch.float32,
    domain=continuous)
>>> spec = Bounded(low=-1, high=1, shape=(), dtype=torch.int)
>>> spec
BoundedDiscrete(
    shape=torch.Size([]),
    space=ContinuousBox(
        low=Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int32, contiguous=True),
        high=Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int32, contiguous=True)),
    device=cpu,
    dtype=torch.int32,
    domain=discrete)
>>> spec.to(torch.float)
BoundedContinuous(
    shape=torch.Size([]),
    space=ContinuousBox(
        low=Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, contiguous=True),
        high=Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, contiguous=True)),
    device=cpu,
    dtype=torch.float32,
    domain=continuous)
>>> spec = Bounded(low=-1, high=1, shape=(), dtype=torch.int, domain="continuous")
>>> spec
BoundedContinuous(
    shape=torch.Size([]),
    space=ContinuousBox(
        low=Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int32, contiguous=True),
        high=Tensor(shape=torch.Size([]), device=cpu, dtype=torch.int32, contiguous=True)),
    device=cpu,
    dtype=torch.int32,
    domain=continuous)
assert_is_in(value: Tensor) None

断言张量是否属于盒子,否则引发异常。

参数:

value (torch.Tensor) – 要检查的值。

cardinality() int[source]

规范的基数。

这指的是规范中可能结果的数量。复合规范的基数假定是所有可能结果的笛卡尔积。

clear_device_() T

对所有叶子规范(必须具有设备)来说是一个无操作。

对于 Composite 规范,此方法将擦除设备。

clone() Bounded[source]

创建 TensorSpec 的副本。

contains(item: torch.Tensor | TensorDictBase) bool

如果值 val 可以由 TensorSpec 生成,则返回 True,否则返回 False

有关更多信息,请参阅 is_in()

cpu()

将 TensorSpec 转换为 'cpu' 设备。

cuda(device=None)

将 TensorSpec 转换为 'cuda' 设备。

property device: device

规范的设备。

只有 Composite 规范可以有 None 设备。所有叶子都必须有一个非空设备。

encode(val: np.ndarray | torch.Tensor | TensorDictBase, *, ignore_device: bool = False) torch.Tensor | TensorDictBase

根据指定的规范编码值,并返回相应的张量。

此方法用于那些返回可以轻松映射到 TorchRL 所需域的值(例如,numpy 数组)的环境。如果该值已经是张量,则规范不会改变其值并按原样返回。

参数:

val (np.ndarraytorch.Tensor) – 要编码为张量的值。

关键字参数:

ignore_device (bool, optional) – 如果为 True,将忽略规范设备。这用于在调用 TensorDict(..., device="cuda") 时对张量转换进行分组,这样更快。

返回值:

与所需张量规范匹配的 torch.Tensor。

enumerate() Any[source]

返回可以从 TensorSpec 中获得的所有样本。

样本将沿着第一个维度堆叠。

此方法仅为离散规范实现。

expand(*shape)[source]

返回具有扩展形状的新 Spec。

参数:

*shape (tupleint 可迭代对象) – Spec 的新形状。必须与当前形状可广播:其长度必须至少与当前形状长度一样长,并且其最后一个值也必须一致;即,只有当前维度是单例时,它们才能与当前形状不同。

flatten(start_dim: int, end_dim: int) T

TensorSpec 展平。

有关此方法的更多信息,请查阅 flatten()

classmethod implements_for_spec(torch_function: Callable) Callable

为 TensorSpec 注册 torch 函数重写。

index(index: INDEX_TYPING, tensor_to_index: torch.Tensor | TensorDictBase) torch.Tensor | TensorDictBase[source]

对输入张量进行索引。

此方法用于编码一个或多个类别变量(例如 OneHotCategorical)的规范,这样就可以在使用样本对张量进行索引时,不必关心索引的实际表示形式。

参数:
  • index (int, torch.Tensor, slicelist) – 张量的索引

  • 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: Tensor) bool[source]

如果值 val 可以由 TensorSpec 生成,则返回 True,否则返回 False

更准确地说,is_in 方法检查值 val 是否在由 space 属性(即盒子)定义的限制范围内,并且检查 dtypedeviceshape 以及可能的其他元数据是否与规范的匹配。如果任何检查失败,is_in 方法将返回 False

参数:

val (torch.Tensor) – 要检查的值。

返回值:

布尔值,指示值是否属于 TensorSpec 盒子。

make_neg_dim(dim: int) T

将特定维度转换为 -1

property ndim: int

规范形状的维度数量。

len(spec.shape) 的快捷方式。

ndimension() int

规范形状的维度数量。

len(spec.shape) 的快捷方式。

one(shape: torch.Size = None) torch.Tensor | TensorDictBase

返回盒子里填充了 1 的张量。

注意

即使不能保证 1 属于规范域,当违反此条件时,此方法也不会引发异常。one 的主要用例是生成空数据缓冲区,而不是有意义的数据。

参数:

shape (torch.Size) – 填充 1 的张量的形状

返回值:

在 TensorSpec 盒子中采样的填充了 1 的张量。

ones(shape: torch.Size = None) torch.Tensor | TensorDictBase

one() 的代理。

project(val: torch.Tensor | TensorDictBase) torch.Tensor | TensorDictBase

如果输入张量不在 TensorSpec 盒子中,它会根据一些定义的启发式方法将其映射回盒子。

参数:

val (torch.Tensor) – 要映射到盒子的张量。

返回值:

属于 TensorSpec 盒子的 torch.Tensor。

rand(shape: Optional[Size] = None) Tensor[source]

在由规范定义的空间中返回一个随机张量。

采样将在空间上均匀进行,除非盒子是无界的,在这种情况下将抽取正态分布的值。

参数:

shape (torch.Size) – 随机张量的形状

返回值:

在 TensorSpec 盒子中采样的随机张量。

reshape(*shape) T

重塑 TensorSpec

有关此方法的更多信息,请查阅 reshape()

sample(shape: torch.Size = None) torch.Tensor | TensorDictBase

在由规范定义的空间中返回一个随机张量。

有关详细信息,请参阅 rand()

squeeze(dim: int | None = None)[source]

返回一个新 Spec,其中所有大小为 1 的维度都被移除。

当给定 dim 时,仅在该维度执行 squeeze 操作。

参数:

dim (intNone) – 应用 squeeze 操作的维度

to(dest: Union[dtype, device, str, int]) Bounded[source]

将 TensorSpec 转换为设备或数据类型(dtype)。

如果未做更改,则返回相同的规范。

to_numpy(val: torch.Tensor | TensorDictBase, safe: bool = None) np.ndarray | dict

返回输入张量对应的 np.ndarray

这旨在成为 encode() 的逆操作。

参数:
  • val (torch.Tensor) – 要转换为 numpy 的张量。

  • safe (bool) – 布尔值,指示是否应针对规范域对值执行检查。默认为 CHECK_SPEC_ENCODE 环境变量的值。

返回值:

一个 np.ndarray。

type_check(value: Tensor, key: Optional[NestedKey] = None) None

检查输入值的数据类型 dtype 是否与 TensorSpecdtype 匹配,如果不匹配则引发异常。

参数:
  • value (torch.Tensor) – 需要检查数据类型(dtype)的张量。

  • key (str, optional) – 如果 TensorSpec 有键,将根据指定的键指向的规范检查值的数据类型(dtype)。

unflatten(dim: int, sizes: Tuple[int]) T

将一个 TensorSpec 展平。

有关此方法的更多信息,请查阅 unflatten()

unsqueeze(dim: int)[source]

返回一个新的 Spec,增加一个单例维度(在由 dim 指示的位置)。

参数:

dim (int or None) – 应用 unsqueeze 操作的维度。

view(*shape) T

重塑 TensorSpec

有关此方法的更多信息,请查阅 reshape()

zero(shape: torch.Size = None) torch.Tensor | TensorDictBase

返回在此(规格定义的)范围内的一个全零张量。

注意

尽管不能保证 0 属于规格域,但当违反此条件时,此方法不会引发异常。zero 的主要用例是生成空数据缓冲区,而不是有意义的数据。

参数:

shape (torch.Size) – 全零张量的形状

返回值:

在此 TensorSpec 范围内生成的一个全零张量。

zeros(shape: torch.Size = None) torch.Tensor | TensorDictBase

zero() 的别名。

文档

查阅 PyTorch 的完整开发者文档

查看文档

教程

获取面向初学者和高级开发者的深度教程

查看教程

资源

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

查看资源