在神经网络中,参数默认是进行随机初始化的。不同的初始化参数往往会导致不同的结果,当得到比较好的结果是,希望这个结果可以复现,在pytorch中,通过设置随机数种子的方法来实现。
import torch
seed = 2020
torch.cuda.manual_seed(seed)
a = torch.rand([1, 2])
b = torch.rand([1, 2])
print(a, b)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
print(a, b, c)
- CPU设置随机数生成种子
torch.manual_seed(args.seed)
- 单GPU设置随机数生成种子
if args.cuda:
torch.cuda.manual_seed(args.seed)
- 多GPU设置随机数生成种子
if args.cuda:
torch.cuda.manual_seed_all(args.seed)
参考资料
torch.manual_seed(args.seed)的作用
torch随机数 manual_seed
利用随机数种子来使pytorch中的结果可以复现