Shortcuts

属性

class torch.jit.Attribute(value, type)[源代码]

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

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

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

  • 可选类型如 Optional[T] 但被赋予了类型 T 的有效值,TorchScript 会假设它是类型 T 而不是 Optional[T]

在急切模式下,它只是一个传递函数,返回而没有其他影响。

示例:

import torch
from typing import Dict

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

        # 我们应该能够在这里将 self.foo 用作浮点数
        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 将包含两个属性
# 1. foo 类型为 float
# 2. names_ages 类型为 Dict[str, int]

注意:现在更推荐使用类型注解来代替torch.jit.Attribute

import torch
from typing import Dict

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

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

m = AttributeModule()
Parameters
  • – 要分配给属性的初始值。

  • 类型 – 一个 Python 类型

Returns

返回

count(value, /)

返回值出现的次数。

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

返回值的第一个索引。

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

type

字段编号1的别名

value

字段编号0的别名