pytorch保证每次运行使用的随机数都相同的方法

其实在代码的开头添加下面几句话即可:

# 保证训练时获取的随机数都是一样的
init_seed = 1
torch.manual_seed(init_seed)
torch.cuda.manual_seed(init_seed)
np.random.seed(init_seed) # 用于numpy的随机数

 

torch.manual_seed(seed)

为了生成随机数设置种子。返回一个torch.Generator对象

参数:

seed (int) – 期望的种子数

 

torch.cuda.manual_seed(seed)

为当前GPU生成随机数设置种子。如果CUDA不可用,调用该方法也是安全的;在这种情况下,该调用就会被忽略

参数:

seed (int) – 期望的种子数

⚠️如果你使用的是多GPU模型,就要调用manual_seed_all(seed).

 

 

 

 

 

 

 

 

posted @ 2019-09-12 18:13  慢行厚积  阅读(3706)  评论(2编辑  收藏  举报