运行时错误:张量的元素 0 不需要 grad 并且没有 grad_fn

问题描述 投票:0回答:1

当我运行程序时,出现此错误:

运行时错误:张量的元素 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()
pytorch gradient torch backpropagation loss-function
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.