前言
在利用pytorch架构构建神经网络时,常常需要随机初始化权重(weight)和偏置(bias)等参数,为了保证训练模型的可复制化,我们需要在训练模型之前进行随机种子的设定。具体可以分为在CPU训练模型和在GPU训练模型设定随机种子。
一、CPU训练模型的随机种子设定
比如每次运行代码,我都希望通过CPU生成一致的随机数,代码如下
import torch
a = torch.manual_seed(1)
b,c = torch.rand(2), torch.rand(3)
print("The random numbers cpu generates are {} and {} respectively".format(b, c))
那我们分别调用两次以上代码,结果如下
由上可见,对于每次结果,b和c随机生成的数值是不同的,即 b ≠c;但两次调用代码生成的结果是相同的;即b =b, c =c。这就是torch.manual_seed方法的含义。
二、GPU训练模型的随机种子设定
我们采用gpu随机生成种子
代码如下,
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(torch.cuda.is_available())
torch.cuda.manual_seed(1)
b,c = torch.rand(2, device = torch.device("cuda")), torch.rand(3, device = torch.device("cuda"))
print("The random numbers gpu generates are {} and {} respectively".format(b, c))
同理,我们分两次运行上述代码,结果如下
由上可见,对于每次结果,b和c随机生成的数值是不同的,即 b ≠c;但两次调用代码生成的结果是相同的;即b =b, c =c。这就是torch.cuda.manual_seed方法的含义。
【提示:如使用gpu随机生成种子,需提前安装cuda和cudnn;否则报错】