如何在 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