pytorch 是否在 nn.Linear 中自动应用 softmax

Does pytorch apply softmax automatically in nn.Linear

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,对吧?

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

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

特别是当我们使用负对数似然作为损失函数时(在 PyTorch 中,这是 torch.nn.NLLLoss, we can utilize the fact that the derivative of (log-)softmax+NLLL is actually mathematically quite nice and simple, which is why it makes sense to combine the both into a single function/element. The result is then torch.nn.CrossEntropyLoss。再次注意,这只直接应用于网络的最后一层,任何其他计算都不是受任何影响。