【问题标题】:Gradient flow stopped on a combined model梯度流在组合模型上停止
【发布时间】:2020-02-19 02:47:48
【问题描述】:

我遇到了梯度无法在组合网络上反向传播的问题。我检查了很多答案,但找不到这个问题的相关解决方案。如果我们能解决这个问题,我将不胜感激。

我想在这段代码中计算输入数据的梯度:

for i, (input, target, impath) in tqdm(enumerate(data_loader)):
# print(‘input.shape:’, input.shape)
input = Variable(input.cuda(), requires_grad=True)
output = model(input)
loss = criterion(output, target.cuda())
loss = Variable(loss, requires_grad=True)
loss.backward()
print(‘input:’, input.grad.data)

但我得到了错误:

print(‘input:’, input.grad.data)
AttributeError: ‘NoneType’ object has no attribute ‘data’

我的模型是一个组合模型,我从两个预训练模型中加载了参数。 我检查了模型权重的 requires_grad 状态字典,这是真的,但是,模型权重的梯度是无。 是不是因为我加载了导致梯度块的state-dict?

我该如何处理这个问题?

模型结构如下:

class resnet_model(nn.Module):
    def __init__(self, opt):
        super(resnet_model, self).__init__()

        resnet = models.resnet101()
        num_ftrs = resnet.fc.in_features
        resnet.fc = nn.Linear(num_ftrs, 1000)

        if opt.resnet_path != None:
            state_dict = torch.load(opt.resnet_path)
            resnet.load_state_dict(state_dict)
            print("resnet load state dict from {}".format(opt.resnet_path))

        self.model1 = torch.nn.Sequential()

        for chd in resnet.named_children():
            if chd[0] != 'fc':
                self.model1.add_module(chd[0], chd[1])

        self.model2 = torch.nn.Sequential()

        self.classifier = LINEAR_LOGSOFTMAX(input_dim=2048, nclass=200)
        if opt.pretrained != None:
            self.classifier_state_dict = torch.load('../checkpoint/{}_cls.pth'.format(opt.pretrained))
            print("classifier load state dict from ../checkpoint/{}_cls.pth".format(opt.pretrained))
        self.classifier.load_state_dict(self.classifier_state_dict)

        for chd in self.classifier.named_children():
            self.model2.add_module(chd[0], chd[1])

    def forward(self, x):
        x = self.model1(x)

        x = x.view(-1, 2048)

        x = self.model2(x)
        return x

【问题讨论】:

    标签: torch nonetype autograd


    【解决方案1】:

    这个问题解决了这个评论:

    为什么会有这行: loss = Variable(loss, requires_grad=True) ? 不应再使用变量。 所以上面的行应该被删除并标记一个你想要渐变的张量,你可以使用: input = input.cuda().requires_grad_().

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      相关资源
      最近更新 更多