Pytorch “更清洁的使用方法”;带火炬。无“梯度();以表情为条件

Pytorch “更清洁的使用方法”;带火炬。无“梯度();以表情为条件,pytorch,Pytorch,我的代码如下所示: if no_grad_condition: with torch.no_grad(): out=network(input) else: out=network(input) 是否有一种更干净的方法来实现这一点,而无需重复行out=network(input) 我正本着以下精神寻找一些东西: with torch.no_grad(no_grad_condition): out=network(input) OP here:通过写下问题,我明白了

我的代码如下所示:

if no_grad_condition:
  with torch.no_grad():
    out=network(input)
else:
  out=network(input)
是否有一种更干净的方法来实现这一点,而无需重复行
out=network(input)

我正本着以下精神寻找一些东西:

  with torch.no_grad(no_grad_condition):
    out=network(input)

OP here:通过写下问题,我明白了在哪里寻找答案。根据,我们可以使用
set\u grad\u enabled

  with torch.set_grad_enabled(not no_grad_condition):
    out=network(input)