pytorch是否在nn中自动应用softmax

时间:2019-08-15 20:43:34

标签: python deep-learning pytorch activation-function

pytorch中,分类网络模型就是这样定义的,

class Net(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_output):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden)   # hidden layer
        self.out = torch.nn.Linear(n_hidden, n_output)   # output layer

    def forward(self, x):
        x = F.relu(self.hidden(x))      # activation function for hidden layer
        x = self.out(x)
        return x

在这里应用softmax吗?以我的理解,事情应该像

class Net(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_output):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden)   # hidden layer
        self.relu =  torch.nn.ReLu(inplace=True)
        self.out = torch.nn.Linear(n_hidden, n_output)   # output layer
        self.softmax = torch.nn.Softmax(dim=n_output)
    def forward(self, x):
        x = self.hidden(x)      # activation function for hidden layer
        x = self.relu(x)
        x = self.out(x)
        x = self.softmax(x)
        return x

我知道F.relu(self.relu(x))也在应用relu,但是第一段代码并不应用softmax,对吗?

1 个答案:

答案 0 :(得分:0)

引用 @jodag 在他的评论中已经说过的内容,并对其进行扩展以形成完整的答案:

,PyTorch不会自动应用softmax,您随时可以根据需要应用torch.nn.Softmax()但是,softmax有some issues with numerical stability,我们希望尽量避免。一种解决方案是使用log-softmax,但这往往比直接计算要慢。

特别是当我们使用负对数似然作为损失函数时(在PyTorch中,这是torch.nn.NLLLoss,我们可以利用以下事实:(log-)softmax + NLLL的导数实际上是mathematically quite nice简单,这就是将两者合并为一个函数/元素的合理原因,然后是torch.nn.CrossEntropyLoss。同样,请注意,这仅直接适用于网络的最后一层,任何其他计算都是不受任何影响。