一、pytorch 检查模型梯度是否可导
当我们构建复杂网络模型或在模型中加入复杂操作时,可能会需要验证该模型或操作是否可导,即模型是否能够优化,在pytorch框架下,我们可以使用torch.autograd.gradcheck函数来实现这一功能。
首先看一下中关于该函数的介绍:


可以看到官方文档中介绍了该函数基于何种方法,以及其参数列表,下面给出几个例子介绍其使用方法,注意:
tensor需要是双精度浮点型且设置requires_grad = true
第一个例子:检查某一操作是否可导
from torch.autograd import gradcheck
import torch
import torch.nn as nn
inputs = torch.randn((10, 5), requires_grad=true, dtype=torch.double)
linear = nn.linear(5, 3)
linear = linear.double()
test = gradcheck(lambda x: linear(x), inputs)
print("are the gradients correct: ", test)
输出为:
are the gradients correct: true
第二个例子:检查某一网络模型是否可导
from torch.autograd import gradcheck
import torch
import torch.nn as nn
# 定义神经网络模型
class net(nn.module):
def __init__(self):
super(net, self).__init__()
self.net = nn.sequential(
nn.linear(15, 30),
nn.relu(),
nn.linear(30, 15),
nn.relu(),
nn.linear(15, 1),
nn.sigmoid()
)
def forward(self, x):
y = self.net(x)
return y
net = net()
net = net.double()
inputs = torch.randn((10, 15), requires_grad=true, dtype=torch.double)
test = gradcheck(net, inputs)
print("are the gradients correct: ", test)
输出为:
are the gradients correct: true
二、pytorch求导
1.标量对矩阵求导

验证:
>>>import torch
>>>a = torch.tensor([[1],[2],[3.],[4]]) # 4*1列向量
>>>x = torch.tensor([[1,2,3],[5,6,7],[8,9,10],[5,4,3.]],requires_grad=true) #4*3矩阵,注意,值必须要是float类型
>>>b = torch.tensor([[2],[3],[4.]]) #3*1列向量
>>>f = a.view(1,-1).mm(x).mm(b) # f = a^t.dot(x).dot(b)
>>>f.backward()
>>>x.grad #df/dx = a.dot(b^t)
tensor([[ 2., 3., 4.],
[ 4., 6., 8.],
[ 6., 9., 12.],
[ 8., 12., 16.]])
>>>a.grad b.grad # a和b的requires_grad都为默认(默认为false),所以求导时,没有梯度
(none, none)
>>>a.mm(b.view(1,-1)) # a.dot(b^t)
tensor([[ 2., 3., 4.],
[ 4., 6., 8.],
[ 6., 9., 12.],
[ 8., 12., 16.]])
2.矩阵对矩阵求导

验证:
>>>a = torch.tensor([[1,2],[3,4.]]) #2*2矩阵
>>>x = torch.tensor([[1,2,3],[4,5.,6]],requires_grad=true) # 2*3矩阵
>>>f = a.mm(x)
>>>f
tensor([[ 9., 12., 15.],
[19., 26., 33.]], grad_fn=<mmbackward>)
>>>f.backgrad(torch.ones_like(f)) # 注意括号里要加上这句
>>>x.grad
tensor([[4., 4., 4.],
[6., 6., 6.]])
注意:
requires_grad为true的数组必须是float类型
进行backgrad的必须是标量,如果是向量,必须在后面括号里加上torch.ones_like(x)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
小花最可怜