如何在 PyTorch 中估计一维或多维函数的梯度?
要估计函数的梯度,我们可以应用 **torch.gradient()** 函数。此函数使用二阶精确中心差分法估计梯度。我们可以估计一维或多维的梯度。需要估计梯度的函数可以在实数或复数域上定义。在估计梯度的过程中,通过独立估计函数的每个偏导数来估计梯度。
语法
torch.gradient(values)
其中参数 **values** 是表示函数值的张量。
步骤
我们可以使用以下步骤来估计函数的梯度:
导入所需的库。在以下所有示例中,所需的 Python 库为 **torch**。请确保您已安装它。
import torch
定义函数 **f** 和点 **x**。
x = torch.tensor([-1., -2., 3., 4.]) def f(x): return x**3
计算上述定义的函数 **f** 在给定点 **x** 处的取值。
values = f(x)
现在使用 **torch.gradient(values)** 估计函数的梯度。这里 **values** 是上面计算出的张量,表示函数 **f** 在给定点 **x** 处的取值。
grad = torch.gradient(values)
打印包含估计梯度的张量。
print("Estimated Gradients:
", grad)现在让我们举几个例子来演示如何估计函数的梯度。
示例 1
# Python program to estimate the gradient of
# f(x)=x^3 at points [-2, -1, 2, 4]
# Import the required library
import torch
# define the points
x = torch.tensor([-1., -2., 3., 4.])
print("Points
", x)
# define the function
def f(x):
return x**3
# values of the function
values = f(x)
print("Function Value:
", values)
# estimate the gradients of the above function
grad = torch.gradient(values)
# print the gradients above estimated
print("Estimated Gradients:
", grad)输出
Points tensor([-1., -2., 3., 4.]) Function Value: tensor([-1., -8., 27., 64.]) Estimated Gradients: (tensor([-7., 14., 36., 37.]),)
在上面的示例中,我们估计了函数 f(x)=x^3 在点 [-2, -1, 2, 4] 处的梯度。
示例 2
# Python 3 program to estimates the gradient of f(x)=x^2+3
# Import the required library
import torch
# define the points
x = torch.randn(2,2)
print("Points
", x)
# define the function
def f(x):
return x**2+3
# values of the function
values = f(x)
print("Function Value:
", values)
# estimate the gradients of the above function
grad = torch.gradient(values)
# print the gradients above estimated
print("Estimated Gradients:
", grad)
# estimate the gradients of the above function in dim 0
grad_dim0 = torch.gradient(values, dim=0)
# print the gradients above estimated
print("Estimated Gradients in dim 0:
", grad_dim0)
# estimate the gradients of the above function in dim 1
grad_dim1 = torch.gradient(values, dim=1)
# print the gradients above estimated
print("Estimated Gradients in dim 1:
", grad_dim1)输出
Points tensor([[-1.7004, 1.5121], [-0.5974, -1.2117]]) Function Value: tensor([[5.8914, 5.2864], [3.3569, 4.4682]]) Estimated Gradients: (tensor([[-2.5345, -0.8182], [-2.5345, -0.8182]]), tensor([[-0.6050, -0.6050], [ 1.1113, 1.1113]])) Estimated Gradients in dim 0: (tensor([[-2.5345, -0.8182], [-2.5345, -0.8182]]),) Estimated Gradients in dim 1: (tensor([[-0.6050, -0.6050], [ 1.1113, 1.1113]]),)
在上面的示例中,我们估计了函数 f(x)=x^2+3 在不同维度的一些随机点处的梯度。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP