深度学习中常见的损失函数——关于使用与prediction与label的shape说明

目录

1. MSELoss

2. NLLLloss

3. CrossEntropyLoss

4. BCELoss与BCEWithLogitsLoss


1. MSELoss

用于一系列点的回归预测

prediction和label的shape应相同,否则可能会出错,例:

import torch
import torch.nn as nn

prediction = torch.ones(2, 5, 5) // 仅在最后一个维度计算,只需要保证prediction与labels维度一直即可
labels = torch.zeros(2, 5, 5) 
loss_func = nn.MSELoss(reduction="mean") // 默认去均值,可设置为sum
loss = loss_func(prediction, labels)
print(loss)

2. NLLLloss

用于多分类

NLLLoss是指对预测结果取负数,然后以label值为索引取出预测的值,prediction比label多一个维度,label中的值表示prediction各预测结果的索引,举例:

prediction = tensor([[-2.4076, -1.4076, -0.4076],

                                 [-2.4076, -1.4076, -0.4076],

                                [-1.0986, -1.0986, -1.0986]])

label = tensor([0, 0, 1])  // 分别对应-2.4076,-2.4076, -1.0986

输出为:

((-(-2.4076)) + (-(-2.4076)) + (-(-1.0986))) / 3 = tensor(5.9138)

 先对prediction做softmax再取log然后使用NLLLoss进行多分类预测

import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
__prediction = np.array([1, 2, 3, 3, 4, 5, 6, 6, 6]).reshape(3, 3)
_label = np.array([0, 0, 1])
_prediction = torch.tensor(__prediction, dtype=torch.float32)
prediction = torch.log(F.softmax(input=_prediction, dim=1))
label = torch.tensor(_label, dtype=torch.int64)
loss_func = nn.NLLLoss()
loss = loss_func(prediction, label)
print(loss)

3. CrossEntropyLoss

用于多分类

CrossEntropyLoss即为softmax+log+NLLLoss,prediction比label多一个维度,label中的值表示prediction各预测结果的索引

import torch
import torch.nn as nn
import numpy as np
_prediction = np.array([1, 2, 3, 3, 4, 5, 6, 6, 6]).reshape(3, 3)
_label = np.array([0, 0, 1])
prediction = torch.tensor(_prediction, dtype=torch.float32)
label = torch.tensor(_label, dtype=torch.int64)
loss_func = nn.CrossEntropyLoss()
loss = loss_func(prediction, label)
print(loss)

4. BCELoss与BCEWithLogitsLoss

用于二分类,如逻辑回归

prediction与label的shape一致,prediction的shape应为[batch_size, 1],预测结果经sigmoid函数,趋向于为0或者1,label值为0或1

sigmoid + nn.BCELoss = nn.BCEWithLogitsLoss

import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
_prediction = (np.array([1, 2, 3])).reshape(3, 1)
_label = np.array([0, 1, 1]).reshape(3, 1)
prediction = torch.tensor(_prediction, dtype=torch.float32)
# prediction = F.sigmoid(torch.tensor(_prediction, dtype=torch.float32))
print(prediction)
label = torch.tensor(_label, dtype=torch.float32)
loss_func = nn.BCEWithLogitsLoss(reduction="sum")
loss = loss_func(prediction, label)
print(loss)

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值