7.4.1 分类任务损失函数
![图片[1]-7.4 损失函数-大赛人网](https://www.dsrw.com/wp-content/uploads/2026/11/image-312.png)
import torch
import torch.nn as nn
# 真实值
target = torch.tensor([[1], [0], [0]], dtype=torch.float32)
# 预测值
input = torch.randn((3, 1))
prediction = torch.sigmoid(input)
# 实例化损失函数
loss = nn.BCELoss()
print(loss(prediction, target))
![图片[2]-7.4 损失函数-大赛人网](https://www.dsrw.com/wp-content/uploads/2026/11/image-313.png)
在PyTorch中可使用torch.nn.CrossEntropyLoss 实现:
注意:调用torch.nn.CrossEntropyLoss相当于调用了torch.nn.LogSoftmax之后再调用torch.nn.NLLLoss。即使用CrossEntropyLoss时上一层的输出不需要Softmax激活函数,因为该损失函数内会自动处理。
import torch
import torch.nn as nn
# 真实值为标签
target = torch.tensor([1, 0, 3, 2, 5, 4]) # 真实值
input = torch.randn((6, 8)) # 预测值
loss = nn.CrossEntropyLoss() # 实例化损失函数
print(loss(input, target))
# 真实值为概率
target = torch.randn(6, 8).softmax(dim=1) # 真实值
input = torch.randn((6, 8)) # 预测值
loss = nn.CrossEntropyLoss() # 实例化损失函数
print(loss(input, target))
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END















请登录后查看评论内容