功能
在神经网络中,参数默认是进行随机初始化的。不同的初始化参数往往会导致不同的结果,当得到比较好的结果时我们通常希望这个结果是可以复现的。总的来说:设置生成随机数的种子,方便复现结果。
示例
借助rand()函数讲解,我们都知道rand()函数是生成随机数的,每次运行程序都会生成随机数。
1.不使用torch.manual_seed()设置随机种子
print(torch.rand(5))
结果:每次运行程序都生成不同的数值
第一次生成的:tensor([0.9884, 0.3207, 0.6428, 0.6181, 0.8697])
第二次生成的:tensor([0.5723, 0.0628, 0.8032, 0.3275, 0.4188])
第三次生成的:tensor([0.5813, 0.4200, 0.1800, 0.9778, 0.6354])
2.使用torch.manual_seed()设置随机种子
import torch
torch.manual_seed(1)
print(torch.rand(5))
结果:程序每次运行程序都是生成一样的数值(无论运行多少次)
tensor([0.7576, 0.2793, 0.4031, 0.7347, 0.0293])
3.设置torch.manual_seed()后,不是每个rand()函数都生成一样的数据,而是同一个rand()函数在每次运行程序时,生成的数据一样
import torch
torch.manual_seed(1)
print(torch.rand(5))
print(torch.rand(5))
结果:每次运行程序,都生成这两组数据(各生成各的)
tensor([0.7576, 0.2793, 0.4031, 0.7347, 0.0293])
tensor([0.7999, 0.3971, 0.7544, 0.5695, 0.4388])
注意:
如果多加一个torch.manual_seed(1),则两个rand()生成的数据一样
import torch
torch.manual_seed(1)
print(torch.rand(5))
torch.manual_seed(1)
print(torch.rand(5))
结果:
tensor([0.7576, 0.2793, 0.4031, 0.7347, 0.0293])
tensor([0.7576, 0.2793, 0.4031, 0.7347, 0.0293])