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)
相关推荐
AI蜗牛之家3 小时前
Qwen系列之Qwen3解读:最强开源模型的细节拆解
人工智能·python
殇者知忧3 小时前
【论文笔记】若干矿井粉尘检测算法概述
深度学习·神经网络·算法·随机森林·机器学习·支持向量机·计算机视觉
whyeekkk3 小时前
python打卡第48天
开发语言·python
SpikeKing5 小时前
Server - 使用 Docker 配置 PyTorch 研发环境
pytorch·docker·llm
Eiceblue5 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
红衣小蛇妖6 小时前
神经网络-Day45
人工智能·深度学习·神经网络
weixin_527550406 小时前
初级程序员入门指南
javascript·python·算法
JoannaJuanCV6 小时前
BEV和OCC学习-5:数据预处理流程
深度学习·目标检测·3d·occ·bev
程序员的世界你不懂6 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP7 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链