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

为了创建具有梯度的张量,我们在创建张量时使用了一个额外的参数“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)