固定住深度模型训练中的所有随机种子

1.为了进行论文复现,或者进行模型的改进,固定住随机种子十分必要,不然所作的改进的提升效果无从知晓,以下代码可以确保每次训练的过程一摸一样

def seed_torch(seed=42):
    seed = int(seed)
    random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.enabled = True
  torch.backends.cudnn.enabled = True  #pytorch 使用CUDANN 加速,即使用GPU加速
  torch.backends.cudnn.benchmark = False #cuDNN使用的非确定性算法自动寻找最适合当前配置的高效算法,设置为False 则每次的算法一致
  torch.backends.cudnn.deterministic=True # 设置每次返回的卷积算法是一致的
  torch.manual_seed(seed)  #为当前CPU 设置随机种子
  torch.cuda.manual_seed(seed)  # 为当前的GPU 设置随机种子
  torch.cuda.manual_seed_all(seed)  #当使用多块GPU 时,均设置随机种子

你可能感兴趣的:(深度学习,神经网络)