当我运行该程序时,我收到以下错误:
运行时错误:Tensor的元素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条答案
按热度按时间0yycz8jy1#
我遇到了同样的错误,
requires_grad = True
,没有工作。如果你想能够通过你的第一次调用.grad(为你的梯度惩罚获得梯度),你需要给予它create_graph=True
。我相信你提到的错误不是完整的错误,如果你的错误是:然后转到“tensor.py“文件并将
create_graph = False
更改为create_graph = True