深度学习常用损失函数介绍和使用

1. nn.L1Loss

取预测值和真实值的绝对误差的平均数

注意数据类型为:double或float

import torch.nn as nn 
import torch 
import numpy as np  
x=np.array([1,2,4]) 
label=torch.from_numpy(x).double() 
pre=torch.ones([3]).double() 
loss=nn.L1Loss() 
print(loss(label,pre))  #1.3333

2. nn.SmoothL1Loss

分段计算误差

import torch.nn as nn
import torch
import numpy as np

x=np.array([1,2,4])
label=torch.from_numpy(x).double()
pre=torch.ones([3]).double()
loss=nn.SmoothL1Loss()
print(loss(label,pre))  #1

3. nn.MSELoss

预测值和真实值之间的平方和的平均数

import torch.nn as nn
import torch
import numpy as np

x=np.array([1,2,4])
label=torch.from_numpy(x).double()
pre=torch.ones([3]).double()
loss=nn.MSELoss()
print(loss(label,pre))  #3.3333

4. nn.NLLLoss()

负对数似然损失函数  Negative Log Likelihood

import torch.nn as nn
import torch
import numpy as np

x=np.ones([2,3])   #input is of size N x C = 2 x 3
x[0][1]=3
label=torch.from_numpy(x)
pre=torch.ones([2]).long()
loss=nn.NLLLoss()
print(loss(label,pre))  #-2

注意:输入格式为N*C; label类型为long()

5. nn.CrossEntropyLoss()

交叉熵损失函数

import torch.nn as nn
import torch
import numpy as np

x=np.ones([2,3])   #input is of size N x C = 2 x 3
x[0][1]=3
label=torch.from_numpy(x)
pre=torch.ones([2]).long()
loss=nn.CrossEntropyLoss()
print(loss(label,pre))  #0.6691

手动计算:

注意:等价于nn.LogSoftmax() 和 nn.NLLLoss()的整合使用

 

注意: 上述代码中label和pre变量名起反了

 

1. nn.LogSoftmax()

import torch.nn as nn
import torch
import numpy as np

x=np.ones([2,3])   #input is of size N x C = 2 x 3
x[0][1]=3
pre=torch.from_numpy(x)
m=nn.LogSoftmax()
lable=torch.ones([2]).long()
loss=nn.NLLLoss()
print(loss(m(pre),lable))

2. nn.Softmax()

import torch.nn as nn
import torch
import numpy as np

x=np.ones([2,3])   #input is of size N x C = 2 x 3
x[0][1]=3
pre=torch.from_numpy(x)
m=nn.Softmax()
print(m(pre))

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值