PyTorch torch.gradient function
PyTorch torch reference manual
torch.gradient A function in PyTorch for computing the gradient of a tensor.
Function definition
torch.gradient(input, *, dim=None, spacing=1, edge_order=1)
Usage examples
Example
import
torch
Create a 1D tensor
x
=
torch.
tensor
(
[
1.0
,
2.0
,
4.0
,
7.0
,
11.0
]
)
Compute gradients
grad
=
torch.
gradient
(
x
)
(
"Gradient:"
,
grad
[
0
]
)
The output is:
梯度: tensor([1., 2., 3., 4.])