RuntimeError:张量的元素0不需要grad并且没有grad_fn

时间:2019-12-02 10:16:48

标签: pytorch gradient torch backpropagation loss-function

运行程序时出现此错误:

  

RuntimeError:张量的元素0不需要grad并且没有grad_fn

但是我设置了gen_y = torch.tensor(gen_y,requires_grad=True),但这没有帮助,gen_y.grad_fn为None。而且我还尝试了x = torch.tensor(x,requires_grad=True),它也不起作用。我猜可能是与pytorch版本有关的问题。我该如何解决这个问题?

    def training(self, net, datasets):
        """
          input:
            net: (object) model & optimizer
            datasets : (list) [train, val] dataset object
        """
        args = self.args
        net.model.train()
        steps = len(datasets[0]) // args.batch_size
        if args.trigger == 'epoch':
            args.epochs = args.terminal
            args.iters = steps * args.terminal
            args.iter_interval = steps * args.interval
        else:
            args.epochs = args.terminal // steps + 1
            args.iters = args.terminal
            args.iter_interval = args.interval

        train_loss, train_acc = 0, 0
        start = time.time()
        for epoch in range(1, args.epochs + 1):
            self.epoch = epoch
            # setup data loader
            data_loader = DataLoader(datasets[0], args.batch_size, num_workers=4,
                                     shuffle=True)
            batch_iterator = iter(data_loader)
            for step in range(steps):
                self.iter += 1
                if self.iter > args.iters:
                    self.iter -= 1
                    break
                # convert numpy.ndarray into pytorch tensor
                x, y = next(batch_iterator)
                x = Variable(x)
                #None
                y = Variable(y)
                if args.cuda:
                    x = x.cuda()
                    y = y.cuda()
                # training
                x = torch.tensor(x,requires_grad=True)
                gen_y = net.model(x)
                gen_y = torch.tensor(gen_y,requires_grad=True)
                print(gen_y.requires_grad)
                print(gen_y.grad_fn)
                if self.is_multi:
                    gen_y = gen_y[0]
                    y = y[0]
                loss = F.binary_cross_entropy(gen_y, y)
                # Update generator parameters

                net.optimizer.zero_grad()
                loss.backward()

1 个答案:

答案 0 :(得分:0)

我遇到了相同的错误,requires_grad = True没有起作用。如果您希望能够后退第一次调用.grad(以获取梯度罚分的梯度),则需要给它create_graph=True。我相信您提到的错误不是完整的错误,如果您的错误是:

> usr/local/lib/python3.6/dist-packages/torch/autograd/__init__.py in.
    backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables)
         97     Variable._execution_engine.run_backward(
               tensors, grad_tensors, retain_graph, create_graph,
    ---> 99         allow_unreachable=True)  # allow_unreachable flag

然后转到“ tensor.py”文件,将create_graph = False更改为create_graph = True