现在位置: 首页 > PyTorch 教程 > 正文

PyTorch torch.gradient 函数


Pytorch torch 参考手册 Pytorch torch 参考手册

torch.gradient 是 PyTorch 中用于计算张量梯度的函数。

函数定义

torch.gradient(input, *, dim=None, spacing=1, edge_order=1)

使用示例

实例

import torch

# 创建一维张量
x = torch.tensor([1.0, 2.0, 4.0, 7.0, 11.0])

# 计算梯度
grad = torch.gradient(x)
print("梯度:", grad[0])

输出结果为:

梯度: tensor([1., 2., 3., 4.])

Pytorch torch 参考手册 Pytorch torch 参考手册