# 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
。