torch.nn中的L1Loss和MSELoss

我们打开Pytorch官网,找到torch.nn中的loss function,进去如下图所示。

L1LOSS

我们先来看看 L1LOSS 损失函数的使用。下图是官网给出的描述。

L1loss有两种方式,一种是将所有误差累加作为总损失,另一种是将所有误差累加之后求平均作为总损失。

例如,给定输入为input = 1,2,3,期望目标为target = 1,2,5,若L1loss采用累加求和求总损失,那么会有总损失L=|1-1|+|2-2|+|5 -3|=2。如示例2所示。

若L1loss采用累计求和后求平均作为总损失,那么则有总损失L=(|1-1|+|2-2|+|5 -3|)/3=0.6667。如示例1所示。

我们用代码来实现L1loss功能。

示例1:L1loss的方式为累加求和后求平均。

python 复制代码
import torch
from torch.nn import L1Loss
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()
result = loss(inputs, targets)
print(result) # tensor(0.6667)

示例2:L1loss的方式为累加求和。 此时L1loss中的参数reduction应为 'sum'。默认为'mean'。

python 复制代码
import torch
from torch.nn import L1Loss
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) # tensor(2.)

MSELOSS

我们再来看看 MSELOSS 损失函数的使用。下图是官网给出的描述。

MSELOSS 与 L1LOSS唯一的区别是MSELOSS在计算每一项损失时都考虑平方。我们以上面的例子为例。

给定输入为input = 1,2,3,期望目标为target = 1,2,5,若MSEloss采用累加求和求总损失,那么会有总损失L=(1-1)^2+(2-2)^2+(5 -3)^2=4。如示例3所示。

若 MSEloss 采用累计求和后求平均作为总损失,那么则有总损失L = {(1-1)^2+(2-2)^2+(5 -3)^2 } /3=4/3。如示例4所示。

示例3

python 复制代码
import torch
from torch.nn import 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 = MSELoss(reduction='sum')
result = loss(inputs, targets)
print(result) # tensor(4.)

示例4

python 复制代码
import torch
from torch.nn import 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 = MSELoss()
result = loss(inputs, targets)
print(result) # tensor(1.3333)
相关推荐
hhzz1 小时前
【OpenCV 入门到精通 04】视频入门与绘图交互:从摄像头到鼠标画笔
人工智能·python·opencv·计算机视觉·音视频·交互
Thomas.Sir1 小时前
第40课:TensorFlow|模型推理部署前置知识【离线推理、接口调用基础】
人工智能·python·tensorflow
2601_962387821 小时前
多源数据查询指南:MySQL 联邦、Python 聚合与 Presto 引擎全对比
python·mysql·数据集成·presto·联邦查询
weixin199701080161 小时前
《Mercari OTA 直连接入:日本二手电商出海的API通道与600次/分钟限流实战》(附Python源码)
开发语言·数据库·python
半亩码田2 小时前
【.NET新特性·第17篇】EF Core 10 与 Aspire 13.1
python·flask·.net
zhangzeyuaaa2 小时前
AI Agent 执行引擎选型指南:PowerShell / Bash 和 Python,边界与最佳实践
人工智能·python·bash
泡干脆面就番茄2 小时前
04_EigenFace特征脸PCA人脸识别
python·opencv
今儿敲了吗2 小时前
01词频统计器
笔记·python
今天AI了吗2 小时前
去中心化 AI 反馈系统:数据不上链,凭证与激励分开管
人工智能·windows·python·数据分析·去中心化·区块链·embedding