with torch.no_grad():
input = Variable(input).cuda()
target = Variable(target).cuda(non_blocking=True)
y=model(input)
# many things here
no_grad 是否在“with”范围之外继续生效?
最佳答案
no_grad
在“with”范围之外没有任何效果。
根据这个answer来自 pytorch 博客的版主:
with torch.no_grad():
# No gradients in this block
x = self.cnn(x)
# Gradients as usual outside of it
x = self.lstm(x)
这就是python中with
语句的作用。 with
使用的变量(此处为 torch.no_grad()
)仅在 with
上下文中有效,之后无效。查看python doc了解完整详情。
关于machine-learning - pytorch 中 with torch.no_grad() 的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60814026/