挥发物已去除,现在无效使用`with torch.no_grad:`代替

问题描述

我尝试将Show And Tell模型与COCO数据集一起使用。但是,有一次我的Torch程序暂停了。谁能修复我的代码?这是我的代码,导致培训暂停。

_image==null?Center(child: Text('Please Upload a pic'),):

警告在下面。

utils.py:114:UserWarning:volatile已删除,现在无效。与torch.no_grad()一起使用:返回变量(x,volatile = volatile)

解决方法

在新版本的Pytorch中,volatile被删除,并且Variable也不必要。 volatile=True不会跟踪使用autograd进行的张量的任何计算。 因此,您的函数可以重写为:

import torch
def to_var(x,volatile=True):
    if torch.cuda.is_available():
        x = x.cuda()
    x.requires_grad = not volatile
    return x

x = torch.tensor(1.0)
print(x.requires_grad)
x = to_var(x,volatile=True)
print(x.requires_grad)
x = to_var(x,volatile=False)
print(x.requires_grad)

输出:

>>> False
>>> False
>>> True