2.0 自動梯度 - PyTorch學習筆記

自動梯度 (AUTOGRAD: AUTOMATIC DIFFERENTIATION)

  1. 導入 torch
import torch
  1. 新建一個需要的2x2張量,並設置梯度記錄爲開啓狀態
x = torch.ones(2, 2, requires_grad=True)
print(x)

輸出:

tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
  1. 進行一個張量操作
y = x + 2
print(y)

輸出:

tensor([[3., 3.],
        [3., 3.]], grad_fn=<AddBackward0>)
  1. 顯示張量的梯度已經被記錄
print(y.grad_fn)

輸出:

<AddBackward0 object at 0x7f1d35f45ef0>
  1. 求均值
z = y * y * 3
out = z.mean()

print(z, out)

輸出:

tensor([[27., 27.],
        [27., 27.]], grad_fn=<MulBackward0>) tensor(27., grad_fn=<MeanBackward0>)
  1. 更改梯度計算參數爲True
a = torch.randn(2, 2)
a = ((a * 3) / (a - 1))
print(a.requires_grad)
a.requires_grad_(True)
print(a.requires_grad)
b = (a * a).sum()
print(b.grad_fn)

輸出:

False
True
<SumBackward0 object at 0x7f1d35f5bb38>
  1. 開始反向傳播
out.backward()
print(x.grad)

輸出:

tensor([[4.5000, 4.5000],
        [4.5000, 4.5000]])
  1. 計算 y 的範數
x = torch.randn(3, requires_grad=True)

y = x * 2
while y.data.norm() < 1000:
    y = y * 2

print(y)

輸出:

tensor([1001.7316,  475.3566, -226.5395], grad_fn=<MulBackward0>)
  1. 計算 x 的梯度
v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)
y.backward(v)

print(x.grad)

輸出:

tensor([1.0240e+02, 1.0240e+03, 1.0240e-01])
  1. 關閉梯度跟蹤
print(x.requires_grad)
print((x ** 2).requires_grad)

with torch.no_grad():
    print((x ** 2).requires_grad)

輸出:

True
True
False
  1. 關閉梯度跟蹤的另一個方式 .detach()
print(x.requires_grad)
y = x.detach()
print(y.requires_grad)
print(x.eq(y).all())

輸出:

True
False
tensor(True)

Ref

https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章