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

本文详细介绍了如何使用PyTorch构建一个前馈神经网络,包括定义网络结构、损失函数、数据预处理及计算损失的过程。并通过实例展示了log-softmax输出与负对数似然损失的运用。
2万+

被折叠的 条评论
为什么被折叠?



