文章目录
前言
本文主要介绍pytorch中常用的损失函数API的使用。
1. 分类损失
1.1. nn.BCELoss()

nn.BCELoss()用于计算二分类问题,使用时采用默认初始化即可,即reduction='mean’是返回loss在所有样本上的均值。在forward方法中,所接受的 input和target必须一样的shape,且target是one-hot编码,而input需提前经过sigmoid处理。
from math import log
import torch
import torch.nn as nn
import torch.nn.functional as F
# 二元交叉熵损失函数,只能处理二分类问题
# 假设处理 二分类问题,且批次=2
input = torch.Tensor([[-1,1],[1,2]]) # input: [2,2]
input = input.sigmoid()
# 转成one-hot
target = torch.Tensor([0,1]) # shape:[2]
onehot_target = torch.eye(2)[target.long(), :]
Loss = nn.BCELoss() # 采用默认初始化
loss1 = Loss(input, onehot_target)
loss2 = F.binary_cross_entropy(input, onehot_target) # 1.0167
1.2. nn.BCEWithLogitsLoss()
该损失函数就是集成了sigmoid的处理,即此时input是直接网络输出即可,不必人为加sigmoid处理。
from math import log
import torch
import torch.nn as nn
import torch.nn.functional as F
# 二元交叉熵损失函数,只能处理二分类问题
# 假设处理 二分类问题,且批次=2
input = torch.Tensor([[-1,1],[1,2]]) # input: [2,2]
# 转成one-hot
target = torch.Tensor([0,1]) # shape:[2]
onehot_target = torch.eye(2)[target.long(), :

本文详细介绍了PyTorch中几种常见的损失函数,包括BCELoss、BCEWithLogitsLoss、多分类交叉熵损失(NLLLoss和CrossEntropyLoss)以及FocalLoss。BCELoss适用于二分类问题,BCEWithLogitsLoss则整合了sigmoid激活函数。对于多分类,可以使用NLLLoss和CrossEntropyLoss,后者更加便捷。FocalLoss通过调整权重,解决了类别不平衡的问题,尤其适合于目标检测等任务。
最低0.47元/天 解锁文章
1万+

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



