我有一个预训练模型,它是通过以下方式保存的:
torch.save(net, 'lenet5_mnist_model')
现在我正在加载它并尝试计算Fisher信息矩阵,如下所示:
precision_matrices = {}batch_size = 32my_model = torch.load('lenet5_mnist_model')my_model.eval() # 我尝试取消注释这一行,但仍然没有效果for n, p in deepcopy({n: p for n, p in my_model.named_parameters()}).items() p = torch.tensor(p, requires_grad = True) p.data.zero_() precision_matrices[n] = variable(p.data)for idx in range(int(images.shape[0]/batch_size)): x = images[idx*batch_size : (idx+1)*batch_size] my_model.zero_grad() x = Variable(x.cuda(), requires_grad = True) output = my_model(x).view(1,-1) label = output.max(1)[1].view(-1) loss = F.nll_loss(F.log_softmax(output, dim=1), label) loss = Variable(loss, requires_grad = True) loss.backward() for n, p in my_model.named_parameters(): precision_matrices[n].data += p.grad.data**2
最终,上述代码会在最后一行崩溃,因为p.grad
是NoneType。因此,错误是:
AttributeError: ‘NoneType’ object has no attribute ‘data’.
有谁能提供一些指导,解释为什么参数的梯度是NoneType?我应该如何修复这个问题?
回答:
你的损失函数没有通过模型反向传播梯度,因为你创建了一个新的损失张量,其值是实际损失的叶节点,这意味着没有历史可以反向传播。
loss.backward()
需要在loss = F.nll_loss(F.log_softmax(output, dim=1), label)
的输出上调用。
我假设你认为需要创建一个requires_grad=True
的张量,才能计算梯度。事实并非如此。用requires_grad=True
创建的张量是计算图的叶节点(它们启动图),对图中任何张量执行的操作都会被跟踪,以便梯度可以通过中间结果流向叶节点。只有需要优化的张量(即可学习参数)应该手动设置requires_grad=True
(模型的参数会自动这样做),关于梯度的一切都是推断出来的。既不是x
也不是loss
是可学习参数。
这种混淆可能是因为使用了Variable
。它在PyTorch 0.4.0中已被弃用,该版本发布已超过两年,其所有功能已合并到张量中。请不要使用Variable
。
x = images[idx*batch_size : (idx+1)*batch_size]my_model.zero_grad()x = x.cuda()output = my_model(x).view(1,-1)label = output.max(1)[1].view(-1)loss = F.nll_loss(F.log_softmax(output, dim=1), label)loss.backward()