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)
相关推荐
仙人掌_lz1 分钟前
详解如何复现LLaMA 4:从零开始利用Python构建
人工智能·python·ai·llama·智能体·ai agents
一个天蝎座 白勺 程序猿7 分钟前
Python(19)Python并发编程:深入解析多线程与多进程的差异及锁机制实战
开发语言·python
星辰大海的精灵10 分钟前
微信客服小助手 python接入
后端·python
AI绘画咪酱12 分钟前
Stable Diffusion【进阶篇】:如何实现人脸一致
人工智能·深度学习·学习·机器学习·ai作画·stable diffusion
补三补四26 分钟前
CNN卷积神经网络
人工智能·深度学习·神经网络·机器学习·cnn
友恒写实1 小时前
Python面试官:你来解释一下协程的实现原理
后端·python
苏牧keio1 小时前
3 Python语法快速入门(基础篇)
python
Watermelo6171 小时前
《Science》观点解读:AI无法创造真正的智能体(AI Agent)
人工智能·深度学习·神经网络·机器学习·语言模型·自然语言处理·数据挖掘
灏瀚星空1 小时前
AI 模型高效化:推理加速与训练优化的技术原理与理论解析
开发语言·人工智能·深度学习·程序人生·机器人·智慧城市·量子计算
hx_long1 小时前
centos7 安装miniconda
python·conda