1

所以,我习惯了使用 PyTorch,现在决定试一试 Skorch。

在这里,他们将网络定义为


class ClassifierModule(nn.Module):
    def __init__(
            self,
            num_units=10,
            nonlin=F.relu,
            dropout=0.5,
    ):
        super(ClassifierModule, self).__init__()
        self.num_units = num_units
        self.nonlin = nonlin
        self.dropout = dropout

        self.dense0 = nn.Linear(20, num_units)
        self.nonlin = nonlin
        self.dropout = nn.Dropout(dropout)
        self.dense1 = nn.Linear(num_units, 10)
        self.output = nn.Linear(10, 2)

    def forward(self, X, **kwargs):
        X = self.nonlin(self.dense0(X))
        X = self.dropout(X)
        X = F.relu(self.dense1(X))
        X = F.softmax(self.output(X), dim=-1)
        return X

我更喜欢在每一层中输入神经元列表,即num_units=[30,15,5,2]有 2 个隐藏层,15 个和 5 个神经元。此外,我们有 30 个特性和 2 个类,因此将其重写为这样的


class Net(nn.Module):
    def __init__(
            self,
            num_units=[30,15,5,2],
            nonlin=[F.relu,F.relu,F.relu],
            dropout=[0.5,0.5,0.5],
            ):
        super(Net, self).__init__()

        self.layer_units = layer_units     
        self.nonlin = nonlin #Activation function
        self.dropout = dropout #Drop-out rates in each layer
        self.layers = [nn.Linear(i,p) for i,p in zip(layer_units,layer_units[1:])] #Dense layers



    def forward(self, X, **kwargs):
        print("Forwards")
        for layer,func,drop in zip(self.layers[:-1],self.nonlin,self.dropout):
            print(layer,func,drop)
            X=drop(func(layer(X)))


        X = F.softmax(X, dim=-1)
        return X


应该做的伎俩。问题是打电话的时候

net = NeuralNetClassifier(Net,max_epochs=20,lr=0.1,device="cuda")
net.fit(X,y)

我收到错误“ValueError:优化器得到一个空的参数列表”。我已将其范围缩小到删除self.output = nn.Linear(10, 2)简单地使网络无法进入forward即它似乎output是某种“触发”变量。网络是否真的需要一个名为output(作为一个层)的变量,并且我们不能自由地自己定义变量名?

4

1 回答 1

0

Pytorch 会寻找 的子类nn.Module,所以改变

self.layers = [nn.Linear(i,p) for i,p in zip(layer_units,layer_units[1:])]

self.layers = nn.ModuleList([nn.Linear(i,p) for i,p in zip(layer_units,layer_units[1:])])

应该可以正常工作

于 2020-04-21T22:29:24.410 回答