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)
相关推荐
Narutolxy6 分钟前
Python 单元测试:深入理解与实战应用20240919
python·单元测试·log4j
Amo Xiang28 分钟前
2024 Python3.10 系统入门+进阶(十五):文件及目录操作
开发语言·python
liangbm338 分钟前
数学建模笔记——动态规划
笔记·python·算法·数学建模·动态规划·背包问题·优化问题
B站计算机毕业设计超人1 小时前
计算机毕业设计Python+Flask微博情感分析 微博舆情预测 微博爬虫 微博大数据 舆情分析系统 大数据毕业设计 NLP文本分类 机器学习 深度学习 AI
爬虫·python·深度学习·算法·机器学习·自然语言处理·数据可视化
羊小猪~~1 小时前
深度学习基础案例5--VGG16人脸识别(体验学习的痛苦与乐趣)
人工智能·python·深度学习·学习·算法·机器学习·cnn
waterHBO3 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七4 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
AI大模型知识分享4 小时前
Prompt最佳实践|如何用参考文本让ChatGPT答案更精准?
人工智能·深度学习·机器学习·chatgpt·prompt·gpt-3
AIAdvocate6 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼6 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt