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

PyTorch学习笔记 - 损失函数

文章目录

  • 1. 内置损失函数
  • 2. 继承 nn.Module 自定义损失函数
  • 3. 继承 autograd.Function 自定义损失函数
  • 3. 三种不同方式实现 MSE 实验

PyTorch 除了内置损失函数,还可以自定义损失函数。我们以均方误差为例来讲解 PyTorch 中损失函数的使用方法。均方误差(Mean Squared Error, MSE)是预测值 x = ( x 1 , x 2 , . . . , x n ) x=(x_1, x_2, ..., x_n) x=(x1,x2,...,xn) 与真实值 y = ( y 1 , y 2 , . . . , y n ) y=(y_1, y_2, ..., y_n) y=(y1,y2,...,yn) 之差的平方和的平均值,数学公式如下:
MSE = 1 n ∑ i = 1 n ( x i − y i ) 2 \text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (x_i - y_i)^2 MSE=n1i=1n(xiyi)2计算 MSE \text{MSE} MSE 损失函数对输入向量 x x x 的梯度如下:
d M S E d x = 2 n ( x − y ) \dfrac{dMSE}{dx} = \dfrac{2}{n}(x-y) dxdMSE=n2(xy)具体而言,
d M S E d x i = 2 n ( x i − y i ) \dfrac{dMSE}{dx_i} = \dfrac{2}{n}(x_i - y_i) dxidMSE=n2(xiyi)

1. 内置损失函数

PyTorch 在 torch.nn 模块中提供了均方误差函数:

import torch.nn as nnmse_loss = nn.MSELoss()

2. 继承 nn.Module 自定义损失函数

只需实现 forward() 方法,无需手动编写反向传播(自动求导引擎处理)。自定义损失函数类实例化后直接调用即可计算损失值。
继承 nn.Module 自定义均方误差损失函数的实现代码如下:

import torch.nn as nnclass MSELossV1(nn.Module):def __init__(self):super().__init__()def forward(self, input, target):squared_diff = (input - target) ** 2n = squared_diff.numel()return squared_diff.sum() / n

3. 继承 autograd.Function 自定义损失函数

在 PyTorch 中,torch.autograd.Function 是一个用于定义自定义自动求导操作的类。它允许用户实现自定义的前向传播forward 和反向传播 backward 逻辑。这对于实现非标准操作、自定义激活函数、或在某些特殊场景中替代现有 PyTorch 操作非常有用。
torch.autograd.Function 实现自定义求导,需要实现 forwardbackward 方法,这意味着需要自己手算反向传播求梯度公式。
ctx 是上下文对象,用于在 forward 和 backward 之间传递数据。常用方法是:

  • ctx.save_for_backward(*tensors):保存张量供反向传播使用
  • ctx.saved_tensors:获取保存的张量

forward 方法返回计算结果,而 backward 返回对每个输入的梯度。
Function.apply(input) 是调用自定义函数的标准方式。继承 autograd.Function 自定义均方误差损失函数的实现代码如下:

import torch
from torch.autograd import Functionclass MSELossV2(Function):@staticmethoddef forward(ctx, input, target):squared_diff = (input - target) ** 2n = squared_diff.numel()ctx.save_for_backward(input, target)return squared_diff.sum() / n@staticmethoddef backward(ctx, grad_output):input, target = ctx.saved_tensorsn = input.numel()grad_input = 2 / n * (input - target) * grad_outputreturn grad_input, None

在 PyTorch 的 torch.autograd.Function 中,backward 方法的返回值数量和顺序必须与 forward 方法的输入参数一一对应。例如,forward 传入的参数为 input 和 target,则 backward 也要返回两个梯度(例如 grad_input, None)。
每个输入参数都需要对应一个梯度输出:

  • 如果输入参数是张量且需要梯度(requires_grad=True),返回其梯度
  • 如果输入参数是整数或不需要梯度的张量,返回 None

backward 中的 grad_output 是一个张量,其形状与当前操作的输出张量一致。它表示在反向传播时,每个输出元素的梯度乘以一个
权重(即 grad_output 的值),从而影响输入梯度的计算。

  • 如果 grad_output 未指定(默认为 None),PyTorch 会假设输出是一个标量,并自动使用全 1 的权重,即 torch.ones_like(output)
  • 如果输出是向量或张量,则必须显式指定 grad_output,否则会报错

grad_output 的使用总结如下:

场景grad_output 的作用示例
标量输出默认为 1,无需显式指定loss.backward()
向量输出必须指定,形状与输出一致y.backward(torch.ones_like(y))
多输出每个输出对应一个 grad_outputgrad_output=[v1, v2]
自定义反向传播传递上层梯度,计算输入梯度backward(ctx, grad_output)

代码示例:

import torchx = torch.tensor([2.0], requires_grad=True)
у = x**2
у.backward()   # 等价于 y.backward(torch.tensor(1.0))
print(x.grad)  # 输出 4.0 (dy/dx = 2x = 4)x2 = torch.tensor([1.0, 2.0], requires_grad=True)
y = x2 * 2
grad_output = torch.tensor([1.0, 0.5])  # 权重分别为 1 和 0.5
y.backward(grad_output)  # x2_grad = tensor([2., 1.]) (grad_output · dy/dx = [1.0, 0.5] · [2., 2.] = [2., 1.])

3. 三种不同方式实现 MSE 实验

实验代码如下:

import torch
import torch.nn as nn
from torch.autograd import Functionclass MSELossV1(nn.Module):def __init__(self):super().__init__()def forward(self, input, target):squared_diff = (input - target) ** 2n = squared_diff.numel()return squared_diff.sum() / nclass MSELossV2(Function):@staticmethoddef forward(ctx, input, target):squared_diff = (input - target) ** 2n = squared_diff.numel()ctx.save_for_backward(input, target)return squared_diff.sum() / n@staticmethoddef backward(ctx, grad_output):input, target = ctx.saved_tensorsn = input.numel()grad_input = 2 / n * (input - target) * grad_outputreturn grad_input, Noneif __name__ == "__main__":mse_loss = nn.MSELoss()mse_loss_v2 = MSELossV1()x = torch.tensor([[1.0, 2.0, 3.0],[4.0, 5.0, 6.0],[7.0, 8.0, 9.0]], requires_grad=True)x2 = x.detach().clone().requires_grad_(True)x3 = x.detach().clone().requires_grad_(True)y = torch.tensor([[0.5, 2.5, 2.0],[3.5, 5.5, 5.0],[6.5, 8.5, 8.0]])loss = mse_loss(x, y)loss2 = mse_loss_v2(x2, y)loss3 = MSELossV2.apply(x3, y)print(f"loss: {loss}, loss2: {loss2}, loss3: {loss3}")loss.backward()loss2.backward()loss3.backward()print(f"x.grad: \n{x.grad}\n x2.grad: \n{x2.grad}\n x3.grad: \n{x3.grad}")

运行结果如下:
在这里插入图片描述
从图中可以看出,三种不同方式实现的均方误差损失函数的计算结果一致。

相关文章:

  • 四、OpenCV图像处理- 视频操作
  • 部分可观察马尔可夫决策过程
  • pytorch 与 张量的处理
  • PH热榜 | 2025-06-04
  • 【每天一个知识点】BP神经网络
  • 鸿蒙应用开发之uni-app x实践
  • 结构性设计模式之Flyweight(享元)
  • 综合案例:斗地主
  • IDEA中微服务指定端口启动
  • Rust 控制流
  • 深度学习之路——CNN卷积神经网络详解
  • Unity性能优化笔记
  • C++——智能指针 weak_ptr
  • 正则表达式检测文件类型是否为视频或图片
  • Linux-文件管理及归档压缩
  • Go语言爬虫系列教程4:使用正则表达式解析HTML内容
  • OPENCV的AT函数
  • 25_05_29docker
  • Windows系统工具:WinToolsPlus 之 SQL Server 日志清理
  • 数据库表中「不是 null」的含义
  • 提升网站的访问速度/seo专家是什么意思
  • 怎样做免费网站推广/网络服务器有哪些
  • 爬黄山旅游攻略游览路线/吉林百度seo公司
  • 做视频网站挣钱吗/有什么引流客源的软件
  • wordpress禁用google字体/南宁seo服务优化
  • 用vue框架做的网站/百度营业执照怎么办理