快捷键

属性 ¶

class torch.jit.Attribute(value, type)[source]

此方法是一个透传函数,返回值,主要用于向 TorchScript 编译器指示左侧表达式是一个具有 type 类型的类实例属性。请注意,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) -> 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(值),start(起始位置,默认为 0),stop(结束位置,默认为 9223372036854775807)。

返回值首次出现的位置。

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

类型

字段编号 1 的别名

字段编号 0 的别名


© 版权所有 PyTorch 贡献者。

使用 Sphinx 构建,并使用 Read the Docs 提供的主题。

文档

PyTorch 的全面开发者文档

查看文档

教程

深入了解初学者和高级开发者的教程

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源