pytorch求hessian

首先有个

网络定义

随意定义了,根据自己的情况

python 复制代码
class ANN(nn.Module):
    def __init__(self):
        super(ANN, self).__init__()
        self.fc1 = nn.Linear(10000, 1)
        # self.fc1.bias.data.fill_(0)
        
    def forward(self, data):
        x = self.fc1(data)
        return x

求hessian

autograd这个方法求梯度的时候分子是scalar ,分母是vector的时候,也即scalar对vector求导,得到的梯度向量和vector一样,而对于vector对vector求导,autograd没法求,只能求scalar对vector求导,所以需要循环。

python 复制代码
def getHessian(grads, model, loss_fn, dat, tar ,device):


    loss = loss_fn(model(dat), tar)
    grads_fn = torch.autograd.grad(loss, model.parameters(), retain_graph=True, create_graph=True) # 记录一阶梯度的grad_fn
 	
 	# 这部分是更新一阶梯度的值,因为其实我要计算的一阶梯度的值是grads
    for source, target in zip(grads, grads_fn):
        target.data.copy_(source)

    hessian_params = []
    #第k个梯度
    for k in range(len(grads_fn)):
        # 第i个参数
        for param in model.parameters():
            hess_params = []
            # 第k个梯度的地i行参数
            for i in range(grads_fn[k].size(0)):
                # 判断是w还是b
                if len(grads_fn[k].size()) == 2:
                    # w
                    for j in range(grads_fn[k].size(1)):  
                        hess = torch.autograd.grad(grads_fn[k][i][j], param, retain_graph=True, allow_unused= True)
                        hess_params.append(hess[0].cpu().detach().numpy() if hess[0] is not None else None)
                else:
                    # b
                    hess = torch.autograd.grad(grads_fn[k][i], param, retain_graph=True, allow_unused=True)
                    hess_params.append(hess[0].cpu().detach().numpy() if hess[0] is not None else None)
            hessian_params.append(np.array(hess_params))
    return hessian_params

关于backward和autograd

autograd只计算梯度不反向传播更新model的参数,因为这部分是torch中的优化器进行的,backward()也计算梯度,但获得具体一阶梯度信息需要用这个命令

grad_list = [p.grad.clone() for p in net.parameters()]

而这样得到的一阶梯度是不含grad_fn的,再进行求导的时候报错,虽然我也尝试loss.backward(retain_graph=True)用了这里的参数,但仍然无法解决问题,所以还是用了autograd。但在模型更新的时候两者使用并不冲突

python 复制代码
 net = ANN()
opt = optim.SGD(net.parameters(), lr=1e-4)


 net.load_state_dict(model_state_dict)
 net.to(device)

 opt.load_state_dict(optimizer_state_dict)
 
 opt.zero_grad()
 
 pred = net(inputs)

 loss = loss_fn(pred, targets)


 grads = torch.autograd.grad(loss, net.parameters(), retain_graph=True, create_graph=True) # 计算一阶梯度

 loss.backward(retain_graph=True)
 opt.step()
  
  ·········
  ······
  #之后进行hessian矩阵的计算就可以

参考

1\] [参考这个博客进行pytorch 求hessian](https://blog.csdn.net/Cyril_KI/article/details/124562109) \[2\] [【矩阵的导数运算】标量向量方程对向量求导_分母布局_分子布局](https://www.bilibili.com/video/BV1av4y1b7MM/?spm_id_from=333.999.0.0&vd_source=2c0021dfb98aee58f7a63ef2d9ad3b48) 此系列三个视频 \[3\] [常用矩阵微分公式_老子今晚不加班的博客-CSDN博客](https://blog.csdn.net/hqh45/article/details/50920904) 这里提到的链接,里面也有提到\[4\]的链接 \[4\] [Matrix calculus - Wikipedia](https://en.wikipedia.org/wiki/Matrix_calculus)这里面总结的很好

相关推荐
Python大数据分析@8 分钟前
Origin、MATLAB、Python 用于科研作图,哪个最好?
开发语言·python·matlab
Cyltcc11 分钟前
如何安装和使用 Claude Code 教程 - Windows 用户篇
人工智能·claude·visual studio code
编程零零七35 分钟前
Python巩固训练——第一天练习题
开发语言·python·python基础·python学习·python练习题
吹风看太阳43 分钟前
机器学习16-总体架构
人工智能·机器学习
Zonda要好好学习1 小时前
Python入门Day4
java·网络·python
moonsims1 小时前
全国产化行业自主无人机智能处理单元-AI飞控+通信一体化模块SkyCore-I
人工智能·无人机
MUTA️2 小时前
ELMo——Embeddings from Language Models原理速学
人工智能·语言模型·自然语言处理
海豚调度2 小时前
Linux 基金会报告解读:开源 AI 重塑经济格局,有人失业,有人涨薪!
大数据·人工智能·ai·开源
小龙在山东2 小时前
Python 包管理工具 uv
windows·python·uv
T__TIII2 小时前
Dify 插件非正式打包
人工智能