当前位置: 首页 > news >正文

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的方式为累加求和后求平均。 

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‘。

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

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

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)
http://www.lryc.cn/news/161805.html

相关文章:

  • Speech | 语音处理,分割一段音频(python)
  • 【深度学习】 Python 和 NumPy 系列教程(三):Python容器:1、列表List详解(初始化、索引、切片、更新、删除、常用函数、拆包、遍历)
  • 【C++笔记】C++string类模拟实现
  • 操作系统之课后习题——引论
  • 【PHP代码审计】反序列化漏洞实战
  • Socks5 与 HTTP 代理在网络安全中的应用
  • 进阶C语言-指针的进阶(中)
  • 保姆级-微信小程序开发教程
  • 数据库-DQL
  • 19 螺旋矩阵
  • 数据结构与算法:概述
  • 顺序表详解
  • 基于RabbitMQ的模拟消息队列之六——网络通信设计
  • 算法:数组中的最大差值---“打擂台法“
  • 三种方式查看 JVM 垃圾收集器
  • React中函数式组件与类组件有何不同?
  • windows11安装docker时,修改默认安装到C盘
  • python模块之 aiomysql 异步mysql
  • 开开心心带你学习MySQL数据库之第八篇
  • yml配置动态数据源(数据库@DS)与引起(If you want an embedded database (H2, HSQL or Derby))类问题
  • yolov5运行过程遇到的小问题(随时更新)
  • 使用FabricJS创建Image对象的JSON表示
  • 【牛客刷题】反转固定区间链表、每k个节点一组反转
  • 算法:数组常见套路1---双指针、取模、打擂台法
  • App 出海实践:Google Play 结算系统
  • 国际慈善日 | 追寻大爱无疆,拓世科技集团的公益之路
  • 关于DNS的一些认识
  • 游戏性能优化
  • 公开游戏、基于有向图的游戏
  • CSS学习笔记05