(三)带权重和ignore_index的交叉熵损失函数

本文详细解析了交叉熵损失函数的计算方法,包括ignore_index参数的使用和带权重交叉熵的应用,通过实例演示如何处理类别不平衡问题。

欢迎访问个人网络日志🌹🌹知行空间🌹🌹


文章目录

背景

使用ADE20K数据集进行验证的分割算法,因这个数据集是exausted annotated,也就是图像中的每个像素都标注了类别,因此背景只占了很少的一部分,因此训练时会设置ignore_index=255,在商汤的框架mmsegmentation中的ade20k.py中的educe_zero_label=True参数,正是为了实现ignore index忽略背景


train_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(type='LoadAnnotations', reduce_zero_label=True),
    dict(type='Resize', img_scale=(2048, 512), ratio_range=(0.5, 2.0))]

解析

正常的交叉熵计算公式为:

l j = y j l o g ( e f y j ∑ i = 1 c e f i ) l_j = y_jlog(\frac{e^{f_{y_j}}}{\sum\limits_{i=1}^{c}e^{f_i}}) lj=yjlog(i=1cefiefyj)

ignore index即需要忽略掉的label id,再计算交叉熵的时候会去除掉ignore index

对于数据:

import torch
y_pre = torch.tensor([[-0.7795, -1.7373, 0.3856],
                      [ 0.4031, -0.5632, -0.2389],
                      [-2.3908,  0.7452, 0.7748]])
y_real = torch.tensor([0, 1, 2])
critien = torch.nn.CrossEntropyLoss()
print(critien(y_pre, y_real))
# tensor(1.2784)

可以将其当成batch=3,类别数C=3的例子,常规交叉熵的计算方式为:

l 1 = 1 ∗ l o g ( e − 0.7795 e − 0.7795 + e − 1.7373 + e 0.3856 ) l_1 = 1 * log(\frac{e^{-0.7795}}{e^{-0.7795}+e^{-1.7373}+e^{0.3856}}) l1=1log(e0.7795+e1.7373+e0.3856e0.7795)
l 2 = 1 ∗ l o g ( e − 0.5632 e 0.4031 + e − 0.5632 + e − 0.2389 ) l_2 = 1 * log(\frac{e^{-0.5632}}{e^{0.4031}+e^{-0.5632}+e^{-0.2389}}) \\ l2=1log(e0.4031+e0.5632+e0.2389e0.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值