记录Pytorch的autograd功能,可能涉及的函数有:
- tensor.requires_grad_(True) #动态修改跟踪
- d = torch.autograd.grad(z, y, grad_outputs=torch.ones_like(y))
- z.backward() #反向传播
创建矩阵Tensor
下面是两种创建Tensor的方法。
x = torch.tensor([[0.0, 1.0], [1.1, 2.2]], requires_grad=True) y = torch.ones(2, 1).clone().detach().requires_grad_(True)
矩阵乘法
直接写 x * y得到的是哈达玛积,可以参考这篇文章《pytorch tensor 乘法运算汇总与解析_程序之巅的博客-CSDN博客_tensor相乘》
利用函数torch.matmul(x, y)求得的才是x和y矩阵相乘的结果。
z = torch.matmul(x, y)
自动微分(求导)
Pytorch提供了强大的API可以对变量进行自动微分。
利用函数torch.autograd.grad(z, x)可以求得\(\frac{\partial z}{\partial x}\),但是如果x是一个矩阵,z也是一个矩阵的话,需要提前规定梯度输出的格式,传入参数grad_outputs=[构造对应大小的全1矩阵]即可。
import torch # 创建图 x = torch.tensor([[0.0, 1.0], [1.1, 2.2]], requires_grad=True) y = torch.ones(2, 1).clone().detach().requires_grad_(True) z = torch.matmul(x, y) k = torch.autograd.grad(z, y, grad_outputs=torch.ones_like(y)) print(k) # 打印: dz/dy
反向传播
通过tensor.backward()方法,可以将某个tensor前面的所有变量全部微分得到梯度,但是只能使用一次,再次使用需要将所有梯度归零且第一次使用要保留图。
import torch x = torch.tensor(2.0, requires_grad=True) z = x ** 3 z.backward() print(x.grad) # 打印: dz/dx
参考文章《pytorch报错详解:RuntimeError: Trying to backward through the graph a second time_糖豆豆今天也要努力鸭的博客-CSDN博客》
Comments NOTHING