如何在 PyTorch 中创建带有梯度的张量?
要创建具有梯度的张量,我们在创建张量时使用额外的参数**"requires_grad = True"**。
**requires_grad**是一个标志,它控制张量是否需要梯度。
只有浮点型和复数类型的张量才能需要梯度。
如果**requires_grad**为假,则该张量与没有**requires_grad**参数的张量相同。
语法
torch.tensor(value, requires_grad = True)
参数
**value** – 张量数据,用户定义或随机生成。
**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("Tensor 1:", tensor1)
print("Tensor 2:", tensor2)输出
Tensor 1: tensor([1., 2., 3.]) Tensor 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("Tensor 1:
", tensor1)
print("Tensor 2:
", tensor2)输出
Tensor 1:
tensor([[-0.9223, 0.1166],
[ 1.6904, 0.6709]])
Tensor 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)
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP