模型引入损失函数
主要介绍三种
- L1Loss
- MSELoss(平方损失函数)
- CrossEntropyLoss(交叉熵损失函数)
L1Loss
对于训练得出的结果和实际的结果target
的作差绝对值作为损失,分为两种情况
- 求出的形式为平均值形式
mean
- 求出的形式为和的形式
sum
这个形式可以在reduction
中指定,默认为平均值mean
形式
我们可以看到其他的两个类的初始化参数已经废弃了,就reduction
还在使用了
我们可以看到需要input
和target
同维度,使用方法为
loss = nn.L1Loss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)
output.backward()
MSELoss
为平方损失函数
具体的定义与L1Loss
相似,唯一的区别就是损失函数的计算变成了input和target差值的平方(L1是差值的绝对值)
CrossEntropyLoss
为交叉熵损失函数
具体的公式定义为
x[class]
代表预测正确的概率class
可以等同于我们之前的target
也分为平均值mean
与总和sum
的方式
使用方法为
>>> loss = nn.CrossEntropyLoss()
>>> input = torch.randn(3, 5, requires_grad=