torch.jit.isinstance
- torch.jit.isinstance(obj, target_type)[源代码]
 - 
    
在TorchScript中提供容器类型的具体化。
它可以处理列表、字典、元组和可选类型的参数化容器。例如:
List[str],Dict[str, List[torch.Tensor]],Optional[Tuple[int,str,int]]。此外,它还可以精炼TorchScript中支持的基本类型,如布尔值和整数。- 参数
 - 
      
- 
        
obj – 需要指定类型的对象
 - 
        
target_type - 试图将对象转换为此目标类型的类型
 
 - 
        
 - 返回值
 - 
      
- 如果 obj 成功转换为 target_type 类型,
 - 
        
否则为 False,不会进行新的类型细化
 
 - 返回类型
 - 
      
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)