PyTorch中特殊函数梯度的计算

PyTorch中特殊函数梯度的计算

普通函数

对于简单的多元函数,对自变量求梯度很容易,例如:
f ( x , y ) = x 2 + y 2 f(x,y)=x^2+y^2 f(x,y)=x2+y2

则有:
{ ∇ x f ( x , y ) = 2 x ∇ y f ( x , y ) = 2 y \left\{ \begin{aligned} \nabla_xf(x,y)&=2x\\ \nabla_yf(x,y)&=2y \end{aligned} \right . {∇xf(x,y)∇yf(x,y)=2x=2y

python 复制代码
import torch
x = torch.tensor([1, 1, 1.0], requires_grad=True)
y = torch.tensor([2, 2, 2.0], requires_grad=True)
z = torch.pow(x, 2) + torch.pow(y, 2)
z.sum().backward()
x.grad, y.grad
python 复制代码
(tensor([2., 2., 2.]), tensor([4., 4., 4.]))

特殊函数

1. Max函数

一般是求几个输入元素的最大值,如何计算梯度呢?
f ( x 0 , x 1 , ... , x n ) = max ⁡ ( x 0 , x 1 , ... , x n ) f(x_0,x_1,\ldots,x_n)=\max(x_0,x_1,\ldots,x_n) f(x0,x1,...,xn)=max(x0,x1,...,xn)

  1. 在数值上求出最大值 a a a

  2. 对函数进行变换
    f ( x 0 , x 1 , ... , x n , a ) = max ⁡ ( x 0 , x 1 , ... , x n , a ) = { a i f x < a x i f x = a f(x_0,x_1,\ldots,x_n,a)=\max(x_0,x_1,\ldots,x_n,a)= \left\{ \begin{aligned} a\quad if\ x<a\\ x\quad if\ x=a \end{aligned} \right. f(x0,x1,...,xn,a)=max(x0,x1,...,xn,a)={aif x<axif x=a

  3. 变换后就可以求梯度了
    ∇ x f ( x , a ) = { 0 i f x < a 1 i f x = a \nabla_x f(x,a)= \left\{ \begin{aligned} 0\quad if\ x<a\\ 1\quad if\ x=a \end{aligned} \right . ∇xf(x,a)={0if x<a1if x=a

在PyTorch中,如果存在多个相等的最大值,那么它们均分"1":

python 复制代码
import torch

x = torch.tensor([1, 2, 3, 4, 4, 0.], requires_grad=True)
y = torch.max(x)
y.backward()
x.grad
python 复制代码
tensor([0.0000, 0.0000, 0.0000, 0.5000, 0.5000, 0.0000])
2. Clip函数

在数据落在一定范围外时,与输入无关
f ( x ) = { x i f a < x < b a i f x < a b i f x > b f(x)= \left\{ \begin{aligned} &x\quad if\ a<x<b\\ &a\quad if\ x<a\\ &b\quad if\ x>b \end{aligned} \right. f(x)=⎩ ⎨ ⎧xif a<x<baif x<abif x>b

python 复制代码
import torch

x = torch.tensor([1, 2, 3, 4, 5, 6, 7.0], requires_grad=True)
y = torch.clip(x, 1.5, 5.5)
y.sum().backward()
x.grad
python 复制代码
tensor([0., 1., 1., 1., 1., 0., 0.])
相关推荐
麦麦大数据17 分钟前
MacOS 安装Python 3.13【同时保留旧版本】
开发语言·python·macos·python安装
美狐美颜sdk1 小时前
直播美颜SDK特效功能实战:从API调用到效果调优的全过程
人工智能·1024程序员节·美颜sdk·直播美颜sdk·第三方美颜sdk
sali-tec4 小时前
C# 基于halcon的视觉工作流-章56-彩图转云图
人工智能·算法·计算机视觉·c#
梦想画家5 小时前
基于PyTorch的时间序列异常检测管道构建指南
人工智能·pytorch·python
Elastic 中国社区官方博客5 小时前
在 Elasticsearch 中使用 Mistral Chat completions 进行上下文工程
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
一碗绿豆汤5 小时前
机器学习第二阶段
人工智能·机器学习
PythonFun6 小时前
OCR图片识别翻译工具功能及源码
python·ocr·机器翻译
用什么都重名6 小时前
DeepSeek-OCR 深度解析
人工智能·ocr·deepseek-ocr
河南骏6 小时前
RAG_检索进阶
人工智能·深度学习
虫师c6 小时前
Python浪漫弹窗程序:Tkinter实现动态祝福窗口教程
python·tkinter·动画效果·gui编程·弹窗效果