PyTorch torch.can_cast 函数

约 459 字 更新于 2026-11-18 5iyo.com

PyTorch torch.can_cast 函数


torch.can_cast 是 PyTorch 中用于检查类型转换是否可执行的函数。检查是否可以从源数据类型转换为目标数据类型。

函数定义

torch.can_cast(from_dtype, to_dtype)

使用示例

实例

import torch

# 检查类型转换是否可执行
print(torch.can_cast(torch.float32, torch.int32))   # True
print(torch.can_cast(torch.float64, torch.int8))    # True
print(torch.can_cast(torch.int64, torch.bool))      # True

# 从 bool 转换
print(torch.can_cast(torch.bool, torch.float32))    # True