zl程序教程

您现在的位置是:首页 >  其它

当前栏目

已解决Runtime Error: one of the variables needed for gradient computation has been modified by an inpla

解决 Error for The of by an has
2023-09-27 14:27:32 时间

已解决Runtime Error: one of the variables needed for gradient computation has been modified by an inplace operation

在这里插入图片描述

报错问题

粉丝群里面的一个小伙伴敲代码时发生了报错(当时他心里瞬间凉了一大截,跑来找我求助,然后顺利帮助他解决了,顺便记录一下希望可以帮助到更多遇到这个bug不会解决的小伙伴),报错信息如下:

Runtime Error: one of the variables needed for gradient computation has been modified by an inplace operation

在这里插入图片描述

解决方法

解决方法如下

在这里插入图片描述
optimizerD.step()对logits_fake进行了修改。直接将其挪到倒数第二行即可,修改后代码为:

for epoch in range(1, epochs + 1):
    for idx, (lr, hr) in enumerate(traindata_loader):
        lrs = lr.to(device)
        hrs = hr.to(device)

        # update the discriminator
        netD.zero_grad()
        logits_fake = netD(netG(lrs).detach())
        logits_real = netD(hrs)
        # Label smoothing
        real = (torch.rand(logits_real.size()) * 0.25 + 0.85).clone().detach().to(device)
        fake = (torch.rand(logits_fake.size()) * 0.15).clone().detach().to(device)
        d_loss = bce(logits_real, real) + bce(logits_fake, fake)
        d_loss.backward(retain_graph=True)
        

        # update the generator
        netG.zero_grad()
        g_loss = contentLoss(netG(lrs), hrs) + adversarialLoss(logits_fake)
        g_loss.backward()   
        optimizerD.step()     
        optimizerG.step()

福利

每周会送6本技术书籍包邮到家
由于博主时间精力有限,每天私信人数太多,没办法每个粉丝都及时回复
大家可以进社区裙或者添加博主微信
点击下方链接即可
http://t.csdn.cn/6kInJ