概述
一个困扰了很久的问题,二分类、多分类、多标签的问题不详述了
- 二分类
- 多分类
- 多标签
损失函数
- Sigmoid和Softmax
Softmax函数得到的值是(0.3, 0.7),代表算法认为”是“的概率是0.7,”否“的概率是0.3,相加为1
Sigmoid函数的输出假如是(0.4, 0.8),它们相加不为1,解释是Sigmoid认为输出第一位为1的概率是0.4,第一位不为1的概率是0.6(1-p),第二位为1的概率是0.8,第二位不为1的概率是0.2
- 损失函数的实现
PyTorch中的实现
给定一组logits
tensor([[ 1.9072, 1.1079, 1.4906],
[-0.6584, -0.0512, 0.7608],
[-0.0614, 0.6583, 0.1095]], requires_grad=True)
对其进行Sigmoid处理
tensor([[0.8707, 0.7517, 0.8162],
[0.3411, 0.4872, 0.6815],
[0.4847, 0.6589, 0.5273]], grad_fn=<SigmoidBackward>)
给定target
tensor([[0., 1., 1.],
[1., 1., 1.],
[0., 0., 0.]])
相当于一个batch中有3个item,手动计算可以得到
import math
r11 = 0 * math.log(0.8707) + (1-0) * math.log((1 - 0.8707))
r12 = 1 * math.log(0.7517) + (1-1) * math.log((1 - 0.7517))
r13 = 1 * math.log(0.8162) + (1-1) * math.log((1 - 0.8162))
r21 = 1 * math.log(0.3411) + (1-1) * math.log((1 - 0.3411))
r22 = 1 * math.log(0.4872) + (1-1) * math.log((1 - 0.4872))
r23 = 1 * math.log(0.6815) + (1-1) * math.log((1 - 0.6815))
r31 = 0 * math.log(0.4847) + (1-0) * math.log((1 - 0.4847))
r32 = 0 * math.log(0.6589) + (1-0) * math.log((1 - 0.6589))
r33 = 0 * math.log(0.5273) + (1-0) * math.log((1 - 0.5273))
r1 = -(r11 + r12 + r13) / 3
#0.8447112733378236
r2 = -(r21 + r22 + r23) / 3
#0.7260397266631787
r3 = -(r31 + r32 + r33) / 3
#0.8292933181294807
bceloss = (r1 + r2 + r3) / 3
print(bceloss)
Out:
0.8000147727101611
- 使用torch内置的loss函数 typeⅠ
该函数要求sigmoid化的logits和target
loss = nn.BCELoss()
print(loss(m(logits), target))
- 使用torch内置的loss函数 typeⅡ
该函数要求原始的logits和target
loss = nn.BCEWithLogitsLoss()
print(loss(logits, target))
Out:
tensor(0.8000, dtype=torch.float64)