【发布时间】:2019-12-22 06:29:06
【问题描述】:
在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,对吧?
【问题讨论】:
-
是的,linear 不会自动应用 softmax。
-
@unlut 谢谢,你觉得第二段代码合适吗?
-
在我看来是正确的。
-
在相关说明中,如果您使用的是
nn.CrossEntropyLoss,则应用 log-softmax,然后是 nll-loss。您可能想确保您没有两次应用 softmax,因为 softmax not idempotent. -
@jodag 谢谢!!!我在@dennlinger 的回答下还有其他问题。希望也能听到您的建议!
标签: python deep-learning pytorch activation-function