快捷键

torch.jit.isinstance

torch.jit.isinstance(obj, target_type)[source][source]

在 TorchScript 中提供容器类型细化。

它可以精炼 List、Dict、Tuple 和 Optional 类型的参数化容器。例如: List[str]Dict[str, List[torch.Tensor]]Optional[Tuple[int,str,int]] 。它还可以精炼 TorchScript 中可用的基本类型,如 bools 和 ints。

参数:
  • obj – 要精炼的对象类型

  • target_type – 尝试将 obj 精炼到的类型

返回值:

如果 obj 成功精炼到 target_type 类型,则为 True

否则为假,没有新的类型细化

返回类型:

bool

示例(使用 torch.jit.isinstance 进行类型细化):.. 测试代码:

import torch
from typing import Any, Dict, List

class MyModule(torch.nn.Module):
    def __init__(self) -> None:
        super().__init__()

    def forward(self, input: Any): # note the Any type
        if torch.jit.isinstance(input, List[torch.Tensor]):
            for t in input:
                y = t.clamp(0, 0.5)
        elif torch.jit.isinstance(input, Dict[str, str]):
            for val in input.values():
                print(val)

m = torch.jit.script(MyModule())
x = [torch.rand(3,3), torch.rand(4,3)]
m(x)
y = {"key1":"val1","key2":"val2"}
m(y)

© 版权所有 PyTorch 贡献者。

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

文档

PyTorch 的全面开发者文档

查看文档

教程

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

查看教程

资源

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

查看资源