随机数种子seed

之前的方案

只在train.py文件里添加了这两句代码,但是还不够

import random
random.seed(42)  # 保证随机结果可复现

现在的方案

在utils.py包里添加

def seed_torch(seed=42):
    random.seed(seed) # Python的随机性
    os.environ["PYTHONHASHSEED"] = str(seed) # 设置python哈希种子,为了禁止hash随机化,使得实验可复现
    np.random.seed(seed) # numpy的随机性
    torch.manual_seed(seed) # torch的CPu随机性,为CPU设置随机种子
    torch.cuda.manual_seed(seed) # torch的GPU随机性,为当前GPU设置随机种子
    torch.cuda.manual_seed_all(seed) # if you are using multi-GPu.torch的GPu随机性,为所有GPU设置随机种子
    torch.backends.cudnn.benchmark = False # if benchmark=True, deterministic will be Falsetorch.backends.cudnn.deterministic = True # 选择确定性算法
    torch.backends.cudnn.deterministic = True # 选择确定性算法

或者

import random
import numpy as np
import torch
def setup_seed(seed):
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    np.random.seed(seed)
    random.seed(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False  # cuDNN's auto-tuner    
seed=42
setup_seed(seed)
# 设置随机种子的代码加在最外层,保证任何随机过程发生之前设置好随机种子。可放在main.py或train.py等训练文件的第一行。

或者

import random
import numpy as np
import torch
import os
def seed_torch(seed=42):
    random.seed(seed) # Python的随机性
    os.environ["PYTHONHASHSEED"] = str(seed) # 设置python哈希种子,为了禁止hash随机化,使得实验可复现
    np.random.seed(seed) # numpy的随机性
    torch.manual_seed(seed) # torch的CPu随机性,为CPU设置随机种子
    torch.cuda.manual_seed(seed) # torch的GPU随机性,为当前GPU设置随机种子
    torch.cuda.manual_seed_all(seed) # if you are using multi-GPu.torch的GPu随机性,为所有GPU设置随机种子
    torch.backends.cudnn.benchmark = False # if benchmark=True, deterministic will be Falsetorch.backends.cudnn.deterministic = True # 选择确定性算法
    torch.backends.cudnn.deterministic = True # 选择确定性算法
seed=42
seed_torch(seed)

添加的位置

由于导包的时候添加载一些模型的时候也会使用随机数,所以设置随机数的的时候尽可能靠前。

参考:

基于pytorch的深度学习网络训练结果复现——重复训练结果一致(随机种子设置) - 知乎

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值