(笔记)Pytorch manual_seed 设置随机数种子

在Pytorch中,神经网络的参数默认是进行随机初始化的,如果不对模型进行设置,则每次训练时的参数都是默认的随机初始化参数,这会导致结果不确定。

        因此,可以使用torch.manual_seed()和torch.cuda.manual_seed()来设置随机数种子,使每次的初始化参数保持固定。

Code:


if args.seed is not None:
    random.seed(args.seed)
    # 为CPU设置种子用于生成随机数,以使结果是确定的
    torch.manual_seed(args.seed)
    # 为当前GPU设置种子用于生成随机数,以使结果是确定的
    torch.cuda.manual_seed(args.seed)
    cudnn.deterministic=True
    
    # 如果使用多个GPU,则为当前所有GPU设置种子
    # torch.cuda.manual_seed_all()

Reference:

  1. 利用随机数种子来使pytorch中的结果可以复现 - 云+社区 - 腾讯云
  2. torch.manual_seed(1)是干嘛用的? - 知乎
  3. (Python 3)Random seed 随机种子_Hanlin的博客-CSDN博客

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