3

Pytorch 中正确的使用 softmax 的方法是什么?

 2 years ago
source link: https://www.v2ex.com/t/816364
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Python

Pytorch 中正确的使用 softmax 的方法是什么?

  LeeReamond · 4 小时 29 分钟前 · 224 次点击

如题,初学者,看官网的 tutorials 中的 quick start ,它是定义了一个长相为这样的网络

        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10)
        )

输出类别为 10 类,然后反向传播的代码是

pred = model(X)
loss = loss_fn(pred, y)

# Backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()

loss_fn 是nn.CrossEntropyLoss()交叉熵,那么这个输出类别似乎是没有通过 softmax 直接就输入交叉熵了吗?

如果要 softmax+交叉熵的话,是应该在定义网络的时候,在最后的 fc 后面再加一个 nn.Softmax(),还是说写成下面这样:

pred = nn.Softmax(model(X))
loss = loss_fn(pred, y)

这个样子?谢谢大家


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK