快捷方式

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 中可用的基本型別,如 bool 和 int。

引數
  • obj – 要細化型別的物件

  • target_type – 嘗試將 obj 細化到的目標型別

返回

如果 obj 成功細化到 target_type 的型別,則為 True,

否則為 False,且沒有新的型別細化

返回型別

bool

示例(使用 torch.jit.isinstance 進行型別細化):.. testcode

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 的全面開發者文件

檢視文件

教程

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

檢視教程

資源

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

檢視資源