PyTorch 种子会影响 dropout 层吗?

Does PyTorch seed affect dropout layers?

我想到了为我的神经网络播种以获得可重现结果的想法,并且想知道 pytorch 播种是否会影响 dropout 层以及为我的 training/testing 播种的正确方法是什么?

我正在阅读文档 here,想知道是否只放置这些行就足够了吗?

torch.manual_seed(1)
torch.cuda.manual_seed(1)

您可以用几行代码轻松回答您的问题:

import torch
from torch import nn

dropout = nn.Dropout(0.5)
torch.manual_seed(9999)
a = dropout(torch.ones(1000))
torch.manual_seed(9999)
b = dropout(torch.ones(1000))
print(sum(abs(a - b)))
# > tensor(0.)

是的,使用manual_seed就够了。

实际上这取决于您的设备:

如果cpu:

  • torch.manual_seed(1) == true.

如果cuda:

  • torch.cuda.manual_seed(1)=true
  • torch.backends.cudnn.deterministic = True

最后,使用以下代码可以确保结果在 python、numpy 和 pytorch 中可重现。

def setup_seed(seed):
    random.seed(seed)                          
    numpy.random.seed(seed)                       
    torch.manual_seed(seed)                    
    torch.cuda.manual_seed(seed)               
    torch.cuda.manual_seed_all(seed)           
    torch.backends.cudnn.deterministic = True  


setup_seed(42)