注意使用 nn.CrossEntropyLoss()作爲損失函數,最後一層輸出不要softmax了,因爲nn.CrossEntropyLoss()已經包含了該操作

# 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

https://classroom.udacity.com/nanodegrees/nd009-cn-advanced/parts/5f4d630c-d15a-412c-aaeb-b57ad61cd03c/modules/3aa9e812-62cd-4ae3-8fc4-593538f08455/lessons/9b014a97-2267-4f1b-af97-284b7dac2a58/concepts/572cd59e-540f-43d9-906f-33d22a4452a6

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章