常用的损失函数

常用的损失函数

L1范数损失

计算 output 和 target 之差的绝对值

torch.nn.L1Loss(reduction='mean'

mean 返回loss和的平均值

sum 返回loss和

均方误差损失 MSELoss(L2)

计算 output 和 target 之差的均方差。

torch.nn.MSELoss(reduction='mean')

mean 返回loss和的平均值

sum 返回loss的和

交叉熵损失 CrossEntropyLoss

常用的交叉熵,以二分类为例:

每个元素的范围为[0,1],若不在该范围内,要对其进行sigmod处理
C E ( p , y ) = { − l o g ( p ) , y = 1 − l o g ( 1 − p ) , o t h e r w i s e CE(p,y)=\begin{cases} -log(p),\quad y=1\\ -log(1-p), otherwise\end{cases} CE(p,y)={log(p)y=1log(1p)otherwise
P t P_t Pt简化交叉熵loss:
P t = { p , i f   y = 1 1 − p , o t h e r w i s e P_t =\begin{cases}p, \quad\quad if \space y=1 \\ 1-p, \quad otherwise\end{cases} Pt={p,if y=11p,otherwise

C E ( p , y ) = C E ( p t ) = − l o g ( p t ) CE(p,y)=CE(p_t)=-log(p_t) CE(p,y)=CE(pt)=log(pt)
与Pt类似,当y=1的时候,αt=α;当y=otherwise的时候,αt=1 - α,a的范围也是0到1。此时我们便可以通过设置α实现控制正负样本对loss的贡献
C E ( p , y , a ) = { − l o g ( p ) ∗ a i f   y = 1 − l o g ( 1 − p ) ∗ ( 1 − a ) i f   y = 0 CE(p,y,a)=\begin{cases} -log(p)*a\quad\quad\quad\quad\quad if\space y=1 \\ -log(1-p)*(1-a) \quad if\space y=0\end{cases} CE(p,y,a)={log(p)aif y=1log(1p)(1a)if y=0

torch.nn.CrossEntropyLoss(weight=None, ignore_index=-100, reduction='mean')

KL 散度损失 KLDivLoss

计算 input 和 target 之间的 KL 散度。KL 散度可用于衡量不同的连续分布之间的距离, 在连续的输出分布的空间上(离散采样)上进行直接回归时 很有效.
D K L ( A ∣ ∣ B ) = ∑ i P A ( x i ) l o g ( P A ( x i ) P B ( x i ) ) D_{KL}(A||B) = \sum_{i}P_A(x_i)log\Big(\frac{P_A(x_i)}{P_B(x_i)} \Big) DKL(AB)=iPA(xi)log(PB(xi)PA(xi))
KL散度主要有两个性质:

(1)不对称性

它不具有对称性,即 D ( A ∣ ∣ B ) ≠ D ( B ∣ ∣ A ) D(A||B)\ne D(B||A) D(AB)=D(BA)$。

(2)非负性

相对熵的值是非负值,即 D ( A ∣ ∣ B ) > 0 D(A||B)>0 D(AB)>0

torch.nn.KLDivLoss(reduction='mean')

二进制交叉熵损失 BCELoss

针对二分类任务。 注意目标 t t t 的值的范围为0到1之间, p p p为output
B C E ( p , t ) = − w ∗ ( t ∗ l n ( p ) + ( 1 − t ) ∗ l n ( 1 − p ) ) BCE(p,t)=-w*(t*ln(p)+(1-t)*ln(1-p)) BCE(p,t)=w(tln(p)+(1t)ln(1p))
当然,还可以使用 w w w来设置你的权重

torch.nn.BCELoss(weight=None, reduction='mean')

BCEWithLogitsLoss

BCEWithLogitsLoss损失函数把 Sigmoid 层集成到了 BCELoss 类中. 该版比用一个简单的 Sigmoid 层和 BCELoss 在数值上更稳定, 因为把这两个操作合并为一个层之后, 可以利用 log-sum-exp 的 技巧来实现数值稳定.

torch.nn.BCEWithLogitsLoss(weight=None, reduction='mean', pos_weight=None)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值