Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PyTorch:仅为参数子集计算Hessian?_Python_Pytorch_Gradient_Loss Function_Hessian - Fatal编程技术网

Python PyTorch:仅为参数子集计算Hessian?

Python PyTorch:仅为参数子集计算Hessian?,python,pytorch,gradient,loss-function,hessian,Python,Pytorch,Gradient,Loss Function,Hessian,我正在编写ElasticWeightConsolidation方法,为此我需要计算Fisher矩阵。据我所知,Fisher矩阵只是通过神经网络的权值来表示可能性的Hessian矩阵。有一个很好的函数,如torch.autograd.functional.hessian(func,inputs,create\u graph=False,strict=False) 所以我想计算hessian(损耗,权重)其中loss=torch.nn.CrossEntropyLoss()。我还准备了网络的权重,这样

我正在编写ElasticWeightConsolidation方法,为此我需要计算Fisher矩阵。据我所知,Fisher矩阵只是通过神经网络的权值来表示可能性的Hessian矩阵。有一个很好的函数,如torch.autograd.functional.hessian(func,inputs,create\u graph=False,strict=False)

所以我想计算
hessian(损耗,权重)
其中
loss=torch.nn.CrossEntropyLoss()
。我还准备了网络的权重,这样它就有了长1D张量,可以简单地取hessian的对角元素,如下所示:

def flat_param(model_param = yann_lecun.parameters()):
  ans_data = []
  ans_data = torch.tensor(ans_data, requires_grad=True)
  ans_data = ans_data.to(device)
  for p in model_param:
    temp_data = p.data.flatten()
    ans_data = torch.cat((ans_data,temp_data))
  return ans_data

ans = flat_param(yann_lecun.parameters())
然后我试着这样做:
hessian(loss,inputs=ans)
但问题是loss也需要目标,但我不想计算其中的hessian。任务是mnist分类,因此目标是整数
0,…,9
如果我在参数中添加
y\u train
,比如
hessian(损失,输入=(ans,y\u train\u 01)


它被“不能从整数中提取梯度”这几个字搞砸了。我还试图使
y\u train\u 01.requires\u grad=False
无效。我知道损失也取决于
y\u train\u 01
,但在我的例子中,有没有办法确定目标是常量?

您可以创建一个新的“包装器”函数,其中目标是固定的:

def原始_型号(功能、目标):
...
返回。。。
def特征可微模型(特征):
固定的目标=。。。
返回原始\u模型(功能、固定\u目标)
然后打电话:

hessian(特征可微模型,特征VAL) 由此产生的二阶偏导数将等效于位置
(功能、固定目标)
处完整Hessian积的类似偏导数