其实在代码的开头添加下面几句话便可:html
# 保证训练时获取的随机数都是同样的 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对象python
参数:安全
seed (int) – 指望的种子数dom
torch.cuda.manual_seed(seed)
为当前GPU生成随机数设置种子。若是CUDA不可用,调用该方法也是安全的;在这种状况下,该调用就会被忽略spa
参数:code
seed (int) – 指望的种子数htm
⚠️若是你使用的是多GPU模型,就要调用manual_seed_all(seed)
.对象