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#
字段编号 1 的别名
- value#
字段编号 0 的别名