BCELoss
torch.nn.BCELoss(weight=None,size_average=True)
weight:控制正样本权重;
size_average:对Loss值取平均。
l
o
s
s
(
o
,
t
)
=
−
1
n
∑
i
(
t
[
i
]
l
o
g
(
o
[
i
]
)
+
(
1
−
t
[
i
]
)
l
o
g
(
1
−
o
[
i
]
)
)
loss(o,t)=-\frac{1}{n}\sum_i(t[i] log(o[i])+(1-t[i]) log(1-o[i]))
loss(o,t)=−n1i∑(t[i]log(o[i])+(1−t[i])log(1−o[i]))
如果weight被指定 :
l
o
s
s
(
o
,
t
)
=
−
1
n
∑
i
w
e
i
g
h
t
s
[
i
]
(
t
[
i
]
l
o
g
(
o
[
i
]
)
+
(
1
−
t
[
i
]
)
∗
l
o
g
(
1
−
o
[
i
]
)
)
loss(o,t)=-\frac{1}{n}\sum_iweights[i] (t[i] log(o[i])+(1-t[i])* log(1-o[i]))
loss(o,t)=−n1i∑weights[i](t[i]log(o[i])+(1−t[i])∗log(1−o[i]))
BCEWithLogitLoss
将BCELoss与Sigmoid融合。
ASRF中,最后的输出应该是没有加Sigmoid的,这会导致数据不在[0,1]之间。
torch.nn.BCEWithLogitsLoss(weight=None, size_average=None, reduce=None, reduction='mean', pos_weight=None)
l
(
x
,
y
)
=
L
=
{
l
1
,
.
.
.
,
l
N
}
T
l(x,y)=L=\{l_1,...,l_N\}^T
l(x,y)=L={l1,...,lN}T
l
n
=
−
ω
n
[
y
n
l
o
g
σ
(
x
n
)
+
(
1
−
y
n
)
l
o
g
(
1
−
σ
(
x
n
)
)
]
l_n = -\omega_n[y_nlog\sigma(x_n)+(1-y_n)log(1-\sigma(x_n))]
ln=−ωn[ynlogσ(xn)+(1−yn)log(1−σ(xn))]
l
(
x
,
y
)
=
m
e
a
n
(
L
)
i
f
r
e
d
u
c
t
i
o
n
=
′
m
e
a
n
′
l(x,y)=mean(L)~if~reduction='mean'
l(x,y)=mean(L) if reduction=′mean′
l
(
x
,
y
)
=
s
u
m
(
L
)
i
f
r
e
d
u
c
t
i
o
n
=
′
s
u
m
′
l(x,y)=sum(L)~if~reduction='sum'
l(x,y)=sum(L) if reduction=′sum′
加入pos_weight后:
l
c
(
x
,
y
)
=
L
c
=
{
l
1
,
c
,
.
.
.
l
N
,
c
}
T
l_c(x,y)=L_c=\{l_{1,c,...l_{N,c}}\}^T
lc(x,y)=Lc={l1,c,...lN,c}T
l
n
,
c
=
−
ω
n
,
c
[
p
c
y
n
,
c
l
o
g
σ
(
x
n
,
c
)
+
(
1
−
y
n
,
c
)
l
o
g
(
1
−
σ
(
x
n
,
c
)
)
]
l_{n,c}=-\omega_{n,c}[p_cy_{n,c}log\sigma(x_{n,c})+(1-y_{n,c})log(1-\sigma(x_{n,c}))]
ln,c=−ωn,c[pcyn,clogσ(xn,c)+(1−yn,c)log(1−σ(xn,c))]
其中n是batch中的样本。
p c > 1 p_c\gt1 pc>1,提高召回率;
p c < 1 p_c\lt1 pc<1,提高精度。
c > 1 c\gt1 c>1,多标签分类;
c < 1 c\lt1 c<1,单标签分类。