# Build a feed-forward network
model = nn.Sequential(nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 10))
# Define the loss
criterion = nn.CrossEntropyLoss()
# Get our data
images, labels = next(iter(trainloader))
# Flatten images
images = images.view(images.shape[0], -1)
# Forward pass, get our logits
logits = model(images)
# Calculate the loss with the logits and the labels
loss = criterion(logits, labels)
print(loss)
使用 nn.LogSoftmax
或 F.log_softmax
(文档)构建具有 log-softmax 输出的模型更方便。然后我们可以通过计算指数 torch.exp(output)
获得实际概率。对于 log-softmax 输出,你需要使用负对数似然损失 nn.NLLLoss
(文档)。
练习:请构建一个返回 log-softmax 输出结果并使用负对数似然损失计算损失的模型。注意,对于
nn.LogSoftmax
和F.log_softmax
,你需要相应地设置dim
关键字参数。dim=0
会计算各行的 softmax,使每列的和为 1,而dim=1
会计算各列的 softmax,使每行的和为 1。思考下你希望输出是什么,并选择恰当的dim
。