如何在 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