概述
用于设置CPU生成随机数的种子。返回一个torch.Generator对象。此时接下来运行随机函数生成的随机数都不会发生变化,方便论文复现结果。
语法
torch.manual_seed(seed)
参数
seed (int) – The desired seed. Value must be within the inclusive range [-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]. Otherwise, a RuntimeError is raised. Negative inputs are remapped to positive values with the formula 0xffff_ffff_ffff_ffff + seed.
代码如下:
import torchprint(torch.rand(1)) # 随机生成[0, 1)的数
每次运行结果都不同:
tensor([0.1580])
tensor([0.9103])
tensor([0.8117])
代码如下:
import torchseed = 1
torch.manual_seed(seed)print(torch.rand(1)) # 随机生成[0, 1)的数
每次运行的结果都一样
tensor([0.7576])
代码如下:
import torchseed = 2
torch.manual_seed(seed)print(torch.rand(1)) # 随机生成[0, 1)的数
每次运行结果都一样:
tensor([0.6147])
将seed改为3:
import torchseed = 3
torch.manual_seed(seed)print(torch.rand(1)) # 随机生成[0, 1)的数
发现运行结果不同:
tensor([0.0043])
代码如下:
import torchseed = 1
torch.manual_seed(seed)print(torch.rand(1)) # 随机生成[0, 1)的数
print(torch.rand(1))
可以看到两次打印 torch.rand(1) 函数生成的随机数结果不同,但每次运行产生的结果还是一致。
tensor([0.7576])
tensor([0.2793])
在每个随机函数前都设置一模一样的随机种子:
import torchseed = 1torch.manual_seed(seed)
print(torch.rand(1)) # 随机生成[0, 1)的数torch.manual_seed(seed)
print(torch.rand(1))
可以看到每次运行的结果都一样:
tensor([0.7576])
tensor([0.7576])
设置不同的随机种子产生不同的随机数,只有随机数一致,每次运行代码产生的随机数就一样(不同机器上运行也一致)。
相当于一个库,不同的种子对应一个随机数库,设置不同的种子就从其对应的库中取数据,从而使得每次运行产生的随机数都一致。
【PyTorch】torch.manual_seed() 详解
本文发布于:2024-01-30 17:31:57,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170660712121676.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |