快捷方式

屬性

class torch.jit.Attribute(value, type)[原始碼]

此方法是一個直通(pass-through)函式,返回 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, /)

返回 value 出現的次數。

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

返回 value 的第一個索引。

如果 value 不存在,則引發 ValueError 錯誤。

type

欄位編號 1 的別名

value

欄位編號 0 的別名

文件

查閱全面的 PyTorch 開發者文件

檢視文件

教程

獲取針對初學者和高階開發者的深入教程

檢視教程

資源

查詢開發資源並獲得問題解答

檢視資源