属性
- 类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]
在急切模式下,它只是一个传递函数,返回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中的一个数据类型
-
- 返回值
-
返回 值
- count(value, /)
-
返回值的数量。
- index(value, start=0, stop=9223372036854775807, /)
-
返回值的首个索引。
若值不存在,则抛出 ValueError 异常。
- 类型
-
字段 1 的别名
- 值
-
字段 0 的别名
-