pytorch 随机数种子

https://zhuanlan.zhihu.com/p/391875795

https://zhuanlan.zhihu.com/p/419063125

可复现性

在硬件设备(CPU、GPU)不同时,完全的可复现性无法保证,即使随机种子相同。但是,在同一个设备上,应该保证可复现性。具体做法是,在程序开始的时候固定torch的随机种子,同时也把numpy的随机种子固定。

np.random.seed(0)
torch.manual_seed(0)
torch.cuda.manual_seed_all(0)

torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False

在工程实践中,我们经常会使用到随机数种子。以深度学习为例,为了能稳定复现各种结果,我们往往需要固定random, np, pytorch(作者是pytorch的小粉丝)的随机数种子。如下写法:

def setup_seed(seed):
     torch.manual_seed(seed)
     torch.cuda.manual_seed_all(seed)
     np.random.seed(seed)
     random.seed(seed)
     torch.backends.cudnn.deterministic = True

一般情况下,对于同一个工程而言,大家知道这个方法就足够了。

posted @ 2022-09-20 06:39  TR_Goldfish  阅读(226)  评论(0编辑  收藏  举报