评价此页

Attribute#

class torch.jit.Attribute(value, type)#

此方法是一个直通函数,返回 value,主要用于指示 TorchScript 编译器左侧表达式是类型为 type 的类实例属性。请注意,torch.jit.Attribute 仅应在 jit.ScriptModule 子类的 __init__ 方法中使用。

尽管 TorchScript 可以为大多数 Python 表达式推断出正确的类型,但在某些情况下类型推断可能会出错,包括:

  • 空容器,如 []{},TorchScript 会假定它们是 Tensor 的容器。

  • 可选类型,如 Optional[T],但被赋了一个类型为 T 的有效值。TorchScript 会假定其类型为 T 而不是 Optional[T]

在 eager 模式下,它仅仅是一个直通函数,返回 value,没有其他含义。

示例

import torch
from typing import Dict

class AttributeModule(torch.jit.ScriptModule):
    def __init__(self) -> None:
        super().__init__()
        self.foo = torch.jit.Attribute(0.1, float)

        # we should be able to use self.foo as a float here
        assert 0.0 < self.foo

        self.names_ages = torch.jit.Attribute({}, Dict[str, int])
        self.names_ages["someone"] = 20
        assert isinstance(self.names_ages["someone"], int)

m = AttributeModule()
# m will contain two attributes
# 1. foo of type float
# 2. names_ages of type Dict[str, int]

注意:现在更推荐使用类型注解而不是 torch.jit.Attribute

import torch
from typing import Dict

class AttributeModule(torch.nn.Module):
    names: Dict[str, int]

    def __init__(self) -> None:
        super().__init__()
        self.names = {}

m = AttributeModule()
参数
  • value – 将分配给属性的初始值。

  • type – 一个 Python 类型。

返回

返回 value

count(value, /)#

返回值的出现次数。

index(value, start=0, stop=9223372036854775807, /)#

返回值的第一个索引。

如果值不存在,则引发 ValueError。

type#

Alias for field number 1

value#

Alias for field number 0