machine-learning - pytorch 中 with torch.no_grad() 的作用域

标签 machine-learning pytorch autograd

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/

相关文章:

python - 如何将 torch.Tensor 替换为 python 中的值

python - 从 numpy 创建张量时缺少梯度

machine-learning - 为什么我们在 train_test_split 的两个数组中都包含目标类?

python - 使用 4 个参数对数据集进行聚类和标记

python - 尝试使用Torch/PyTorch创建Docker镜像时出现MemoryError

python - 如何在pytorch中测试一张图片

python - 评估pytorch模型: `with torch.no_grad` vs `model.eval()`

pytorch - 使用 autograd 计算相对于输入的输出雅可比矩阵

python - Keras CNN 错误 : expected Sequence to have 3 dimensions, 但获得形状为 (500, 400) 的数组

machine-learning - LightGBM 中的 Bagging 是如何工作的