Neural network 在pytorch中添加xavier初始化

Neural network 在pytorch中添加xavier初始化,neural-network,pytorch,Neural Network,Pytorch,我想将Xavier初始化添加到我的神经网络的第一层,但是我在这个类中遇到了一个错误: class DemoNN(nn.Module): def __init__(self): super().__init__() torch.manual_seed(0) self.net = nn.Sequential( nn.Linear(2,2), torch.nn.init.xavier_uniform

我想将Xavier初始化添加到我的神经网络的第一层,但是我在这个类中遇到了一个错误:

class DemoNN(nn.Module):
    def __init__(self):
        super().__init__()
        torch.manual_seed(0)
        self.net = nn.Sequential(
            nn.Linear(2,2),
            torch.nn.init.xavier_uniform((nn.Linear(2,2)).weights),
            nn.Sigmoid(),

            nn.Linear(2,2),
            nn.Sigmoid(),

            nn.Linear(2,4),
            nn.Softmax()
            )
    
    def forward(self, X):
        self.net(X)

您似乎试图在nn.Sequential对象的构造函数中初始化第二个线性层。 您需要做的是首先构造
self.net
,然后根据需要初始化第二个线性层。 以下是您应该如何做到这一点:

import torch
import torch.nn as nn
class DemoNN(nn.Module):
    def __init__(self):
        super().__init__()
        torch.manual_seed(0)
        self.net = nn.Sequential(
            nn.Linear(2,2),
            nn.Linear(2,2),
            nn.Sigmoid(),

            nn.Linear(2,2),
            nn.Sigmoid(),

            nn.Linear(2,4),
            nn.Softmax()
        )
        torch.nn.init.xavier_uniform_(self.net[1].weight)
    
    def forward(self, X):
        self.net(X)

我现在得到一个错误:``` RuntimeError:预期对象为标量类型Float,但在调用` th_addmm``时参数` 2'mat1'得到标量类型Double``请确保网络的输入是1x2张量。例如,一个有效的输入是:input=torch.ones(1,2),然后是net=DemoNN(),后面是net(input),为什么只在第一层上,而不是在整个网络上(我得到了解决方案)