首页 文章资讯内容详情

如何在 PyTorch 中创建具有梯度的张量?

2026-06-02 1 花语

为了创建具有梯度的张量,我们在创建张量时使用了一个额外的参数“requires_grad=True”

requires_grad是控制张量是否需要梯度的标志。

只有浮点和复数dtype张量可以需要梯度。

如果requires_grad为false,则张量与没有requires_grad参数的张量相同。

语法

torch.tensor(value, requires_grad = True)

参数

——张量数据,用户定义的或随机生成的。

requires_grad–一个标志,如果为True,则张量包含在梯度计算中。

输出结果

它返回一个requires_grad为True的张量。

脚步

导入所需的库。所需的库是torch

使用requires_grad=True定义张量

用梯度显示创建的张量。

计算机科学

让我们举几个例子来更好地理解它是如何工作的。

示例1

在以下示例中,我们创建了两个张量。一个张量没有requires_grad=True,另一个是requires_grad=True

# import torch library import torch # create a tensor without gradient tensor1 = torch.tensor([1.,2.,3.]) # create another tensor with gradient tensor2 = torch.tensor([1.,2.,3.], requires_grad = True) # print the created tensors print("张量1:", tensor1) print("张量2:", tensor2)输出结果张量1: tensor([1., 2., 3.]) 张量2: tensor([1., 2., 3.], requires_grad=True)

示例2

# import required library import torch # create a tensor without gradient tensor1 = torch.randn(2,2) # create another tensor with gradient tensor2 = torch.randn(2,2, requires_grad = True) # print the created tensors print("张量1:\n", tensor1) print("张量2:\n", tensor2)输出结果张量1: tensor([[-0.9223, 0.1166], [ 1.6904, 0.6709]]) 张量2: tensor([[ 1.1912, -0.1402], [-0.2098, 0.1481]], requires_grad=True)

示例3

在下面的示例中,我们使用numpy数组创建了一个具有梯度的张量。

# import the required libraries import torch import numpy as np # create a tensor of random numbers with gradients # generate 2x2 numpy array of random numbers v = np.random.randn(2,2) # create a tensor with above random numpy array tensor1 = torch.tensor(v, requires_grad = True) # print above created tensor print(tensor1)输出结果tensor([[ 0.7128, 0.8310], [ 1.6389, -0.3444]], dtype=torch.float64, requires_grad=True)