如何在 PyTorch 中計算梯度?


要計算梯度,張量必須將其引數設定為 **requires_grad = True**。梯度與偏導數相同。

例如,在函式 **y = 2*x + 1** 中,**x** 是一個設定了 **requires_grad = True** 的張量。我們可以使用 **y.backward()** 函式計算梯度,並使用 **x.grad** 訪問梯度。

這裡,**x.grad** 的值與 **y** 關於 **x** 的偏導數相同。如果張量 x 沒有設定 **requires_grad**,則梯度為 None。我們可以定義一個包含多個變數的函式。這裡的變數是 PyTorch 張量。

步驟

我們可以使用以下步驟計算梯度:

  • 匯入 **torch** 庫。確保你已經安裝了它。

import torch
  • 建立具有 **requires_grad = True** 的 PyTorch 張量並列印張量。

x = torch.tensor(2.0, requires_grad = True)
print("x:", x)
  • 為上述張量 **x** 定義函式 **y**。

y = x**2 + 1
  • 使用 **y** 的 **backward** 函式計算梯度。

y.backward()
  • 使用 **x.grad** 訪問並列印關於上述建立的張量 **x** 的梯度。

dx = x.grad
print("x.grad :", dx)

示例 1

以下示例展示了在 PyTorch 中計算梯度的詳細過程。

# import torch library
import torch

# create tensors with requires_grad = true
x = torch.tensor(2.0, requires_grad = True)

# print the tensor
print("x:", x)

# define a function y for the tensor, x
y = x**2 + 1
print("y:", y)

# Compute gradients using backward function for y
y.backward()

# Access the gradients using x.grad
dx = x.grad
print("x.grad :", dx)

輸出

x: tensor(2., requires_grad=True)
y: tensor(5., grad_fn=<AddBackward0>)
x.grad : tensor(4.)

示例 2

在下面的 Python 程式中,我們使用三個張量 **x**、**w** 和 **b** 作為函式 **y** 的變數。張量 **x** 沒有設定 **requires_grad**,而 **w** 和 **b** 設定了 **requires_grad = True**。

# import torch library
import torch

# create tensor without requires_grad = true
x = torch.tensor(3)

# create tensors with requires_grad = true
w = torch.tensor(2.0, requires_grad = True)
b = torch.tensor(5.0, requires_grad = True)

# print the tensors
print("x:", x)
print("w:", w)
print("b:", b)

# define a function y for the above tensors
y = w*x + b
print("y:", y)

# Compute gradients by calling backward function for y
y.backward()

# Access and print the gradients w.r.t x, w, and b
dx = x.grad
dw = w.grad
db = b.grad
print("x.grad :", dx)
print("w.grad :", dw)
print("b.grad :", db)

輸出

x: tensor(3)
w: tensor(2., requires_grad=True)
b: tensor(5., requires_grad=True)
y: tensor(11., grad_fn=<AddBackward0>)
x.grad : None
w.grad : tensor(3.)
b.grad : tensor(1.)

注意,**x.grad** 為 None。這是因為 x 沒有設定 **requires_grad = True**。

示例 3

# import torch library
import torch

# create tensors with requires_grad = true
x = torch.tensor(3.0, requires_grad = True)
y = torch.tensor(4.0, requires_grad = True)

# print the tensors
print("x:", x)
print("y:", y)

# define a function z of above created tensors
z = x**y
print("z:", z)

# call backward function for z to compute the gradients
z.backward()

# Access and print the gradients w.r.t x, and y
dx = x.grad
dy = y.grad
print("x.grad :", dx)
print("y.grad :", dy)

輸出

x: tensor(3., requires_grad=True)
y: tensor(4., requires_grad=True)
z: tensor(81., grad_fn=<PowBackward1>)
x.grad : tensor(108.)
y.grad : tensor(88.9876)

更新於:2021年12月6日

12K+ 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告