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