Python 使用相同种子的不同Pytork随机初始化

Python 使用相同种子的不同Pytork随机初始化,python,random,pytorch,Python,Random,Pytorch,我是Pytorch的新手,所以如果问题很简单,我道歉。 我的问题是我已经定义了类net1,并使用固定的手动种子随机初始化了它的参数 random.seed(opt.manualSeed) torch.manual_seed(opt.manualSeed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(opt.manualSeed) class net1(nn.Module): def __init__(

我是Pytorch的新手,所以如果问题很简单,我道歉。 我的问题是我已经定义了类
net1
,并使用固定的手动种子随机初始化了它的参数

random.seed(opt.manualSeed)
torch.manual_seed(opt.manualSeed)
if torch.cuda.is_available():
    torch.cuda.manual_seed_all(opt.manualSeed)    

class net1(nn.Module):
    def __init__(self):
        super(net1, self).__init__()
        self.main_body = nn.Sequential(
            # Define the layers...#
        )
    def forward(self, x):
        return self.main_body(x)

# custom weights initialization called on net1
def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        m.weight.data.normal_(0.0, 0.02)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.normal_(1.0, 0.02)
        m.bias.data.fill_(0)

net1_ = net1()
net1_.apply(weights_init)
但是,当我向代码中添加另一个类
net2
时:

class net2(nn.Module):
    def __init__(self):
        super(net2, self).__init__()
        self.main_body = nn.Sequential(
            # Define the layers
        )
    def forward(self, x):
        return self.main_body(x)

net2_ = net2()
并实例化它,即使我没有在其他任何地方使用它,也没有连接到我的主图形(它构建在
net1\uuu
上),我从图形中获得不同的输出。
这是一个合理的结果吗?

我假设执行顺序是:

random.seed(opt.manualSeed)
torch.manual_seed(opt.manualSeed)
if torch.cuda.is_available():
    torch.cuda.manual_seed_all(opt.manualSeed)    

if with_net2:
    net2_ = net2()

net1_ = net1()
net1_.apply(weights_init)
如果是这样,这是意料之中的

这是因为当调用
net2.\uuuuu init\uuuu
时(在
net2\=net2()
期间), torch的随机数生成器用于在
net2\uuu
中随机初始化权重。
因此,如果
使用
使用
相比,在执行
net1.apply
时,随机数生成器的状态将不同于
在实例化net2之前第二次修复种子?