1. 手动实现BCELoss损失函数
BCELoss损失函数,又称 “二元交叉熵损失函数(binary cross entropy loss)”
计算公式:
l
o
s
s
(
x
,
c
l
a
s
s
)
=
−
l
o
g
p
(
x
c
l
a
s
s
)
.
loss(x,class) = -{log {p(x_{class})}}.
loss(x,class)=−logp(xclass).
class为x的真实类别标签,因此
x
c
l
a
s
s
x_{class}
xclass是将样本x预测为真实标签的概率。
python代码实现:
def BCE_loss(y_hat, y):
# y_hat:预测标签,已经过sigmoid/softmax处理 shape is (batch_size, 1)
# y:真实标签(一般为0或1) shape is (batch_size)
y_hat = torch.cat((1-y_hat, y_hat), 1) # 将二种情况的概率都列出,y_hat形状变为(batch_size, 2)
# 按照y标定的真实标签,取出预测的概率,来计算损失
return - torch.log(y_hat.gather(1, y.view(-1, 1))).mean()
# 函数返回loss均值
2.手动实现CrossEntropyLoss损失函数
交叉熵损失的数学解释见:交叉熵loss函数
计算公式:
l
o
s
s
(
x
,
c
l
a
s
s
)
=
−
l
o
g
p
(
x
c
l
a
s
s
)
.
loss(x,class) = -{log {p(x_{class})}}.
loss(x,class)=−logp(xclass).
class为x的真实类别标签,因此
x
c
l
a
s
s
x_{class}
xclass是将样本x预测为真实标签的概率。
基本概念同BCE损失函数,只不过从计算二元损失变成了计算多元损失。
python代码实现:
# 自定义softmax运算
def my_softmax(X, dim):
X_exp = X.exp()
partition = X_exp.sum(dim=dim, keepdim=True)
return X_exp / partition # 这里使用了numpy的广播机制
# 定义损失函数
def cross_entropy(y_pre, y):
# y_pre: 预测值未经过softmax处理,shape is (batch_size, class_num)
# y: 真值,shape is (batch_size)
y_pre = my_softmax(y_pre, dim=1)
return - torch.log(y_pre.gather(1, y.view(-1, 1))).mean()
# 返回计算的loss均值