为何torch.rand()设置dtype=torch.int会抛出RuntimeError?
PyTorch中torch.rand指定torch.int报错的原因及解决办法
在Python 3.9.6环境下执行以下代码时,会抛出RuntimeError: "check_uniform_bounds" not implemented for 'Int'错误,但将dtype改为torch.double则能正常运行:
import torch x = torch.rand(2,2,dtype=torch.int) y = torch.rand(2,2,dtype=torch.int) print("x is", x) print("y is", y) z = torch.add(x,y) print(z)
错误输出如下:
x = torch.rand(2,2,dtype=torch.int) Traceback (most recent call last): File "/Training/main.py", line 4, in <module> x = torch.rand(2,2,dtype=torch.int) RuntimeError: "check_uniform_bounds" not implemented for 'Int'
报错原因
torch.rand的核心逻辑是生成**[0, 1)区间内的均匀分布随机数**,这个过程依赖浮点运算实现。而整数类型(如torch.int)无法表示[0,1)之间的小数,PyTorch也就没有为整数类型实现torch.rand对应的均匀分布边界检查及生成逻辑,直接指定整数dtype就会触发这个未实现的错误。
torch.double属于浮点类型,能精准表示[0,1)区间的数值,因此可以正常执行torch.rand。
解决办法
如果需要生成整数类型的随机张量,推荐两种方式:
- 方式一:先生成浮点随机数,再转换为整数(可自定义数值范围)
import torch # 生成[0, 10)区间的整数随机张量 x = torch.rand(2,2) * 10 x = x.to(torch.int) print(x) - 方式二:使用PyTorch专为整数设计的随机函数
torch.randintimport torch # 生成[0, 10)区间的整数随机张量 x = torch.randint(0, 10, (2,2), dtype=torch.int) print(x)
内容的提问来源于stack exchange,提问作者Harish Kannan
相关产品推荐
相关产品推荐

