目录
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)