torch.jit.isinstance¶
- torch.jit.isinstance(obj, target_type)[原始碼][原始碼]¶
在 TorchScript 中提供容器類型精煉。
它可以精煉 List、Dict、Tuple 和 Optional 類型的參數化容器。例如:
List[str]
、Dict[str, List[torch.Tensor]]
、Optional[Tuple[int,str,int]]
。它也可以精煉 TorchScript 中可用的基本類型,例如布林值和整數。- 參數
obj – 要精煉其類型的物件
target_type – 嘗試將 obj 精煉成的類型
- 返回值
- 如果 obj 成功精煉為 target_type 的類型,則為 True。
否則為 False,且沒有新的類型精煉
- 返回類型
bool
範例 (使用
torch.jit.isinstance
進行類型精煉): .. testcodeimport 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)