深度学习中的损失函数与反向传播,有哪些可以深入探讨?

摘要:# 一、损失函数:Loss Function > 官网文档:[torch.nn — PyTorch 2.0 documentation](https:pytorch.orgdocsstablenn.html#
一、损失函数:Loss Function 官网文档:torch.nn — PyTorch 2.0 documentation 1. Loss Function的作用 每次训练神经网络的时候都会有一个目标,也会有一个输出。目标和输出之间的误差,就是用\(Loss\) \(Function\)来衡量的。所以,误差\(Loss\)是越小越好的。 此外,我们可以根据误差\(Loss\),指导输出\(output\)接近目标\(target\)。即我们可以以\(Loss\)为依据,不断训练神经网络,优化神经网络中各个模块,从而优化\(output\)。 \(Loss\) \(Function\)的作用: (1)计算实际输出和目标之间的差距 (2)为我们更新输出提供一定的依据,这个提供依据的过程也叫反向传播。 2. Loss Function中的函数介绍 (1)nn.L1Loss 计算\(MAE\) (mean absolute error),即假设输入为\(x_i\),目标为\(y_i\),特征数量为\(n\)。在默认情况下,\(nn.L1Loss\)通过下面公式计算误差: \[\frac{\sum^{n}_{i=1}{|x_i-y_i|}}{n} \] class torch.nn.L1Loss(size_average=None, reduce=None, reduction='mean') 参数说明: reduction:默认为 ‘mean’ ,可选mean和sum。 当reduction='mean'时,计算误差采用公式: \[\frac{\sum^{n}_{i=1}{|x_i-y_i|}}{n} \] 当reduction='sum'时,计算误差采用公式: \[\sum^{n}_{i=1}{|x_i-y_i|} \] 需要注意的是,计算的数据必须为浮点数。 代码栗子: import torch from torch.nn import L1Loss input=torch.tensor([1,2,3],dtype=torch.float32) target=torch.tensor([1,2,5],dtype=torch.float32) input=torch.reshape(input,(1,1,1,3)) target=torch.reshape(target,(1,1,1,3)) loss1=L1Loss() #reduction='mean' loss2=L1Loss(reduction='sum') #reduction='mean' result1=loss1(input,target) result2=loss2(input,target) print(result1,result2) (2)nn.MSELoss 计算\(MSE\) (mean squared error),即假设输入为\(x_i\),目标为\(y_i\),特征数量为\(n\)。在默认情况下,\(nn.MSELoss\)通过下面公式计算误差: \[\frac{\sum^{n}_{i=1}{(x_i-y_i)^2}}{n} \] class torch.nn.MSELoss(size_average=None, reduce=None, reduction='mean') 参数说明: reduction:默认为 ‘mean’ ,可选mean和sum。
阅读全文