首页 > 其他分享 >19、损失函数与反向传播

19、损失函数与反向传播

时间:2023-02-22 21:36:20浏览次数:33  
标签:函数 L1Loss 19 torch cross 反向 nn targets tensor

1、损失函数

(1)计算实际输出和目标之间的差距;

(2)为更新输出提供一定的依据(反向传播);

Loss Function:

nn.L1Loss:

输入值是x,输出值是y,那么L1Loss是采用  |yi-xi|/x的个数,就是每一个对应的y-x的绝对差值加起来再求平均

 

 

 要关注输入数据尺寸大小

'''1、L1loss'''
import torch
from torch.nn import L1Loss, MSELoss

inputs=torch.tensor([1,2,3],dtype=torch.float32)
targets=torch.tensor([1,2,5],dtype=torch.float32)

inputs=torch.reshape(inputs,(1,1,1,3))
targets=torch.reshape(targets,(1,1,1,3))
loss=L1Loss(reduction='sum')
result=loss(inputs,targets)
print(result)

 

 

 2、nn.MSELoss

 

 

 

 

 

 3、交叉熵  CrossEntropyLoss

针对多个类别的分类任务

 

 

 

 

 

 

'''3、交叉熵'''
x=torch.tensor([0.1,0.2,0.3]) #输入值,也就是每个类别的概率预测值
y=torch.tensor([1]) #目标值,正确的分类标签值
x=torch.reshape(x,(1,3)) #batchsize=1,class=3 3个类别
loss_cross=nn.CrossEntropyLoss()
result_cross=loss_cross(x,y)
print(result_cross)

只有用反向传播,才会有梯度下降,从而更新参数,如果不使用反向传播,是没有梯度的。

 

 

 

 

标签:函数,L1Loss,19,torch,cross,反向,nn,targets,tensor
From: https://www.cnblogs.com/ar-boke/p/17146007.html

相关文章