北京网站制作培训学校,网站开发维护前景,遵义网站搭建公司哪家好,江苏专业网站推广公司在使用pytorch时#xff0c;并不是所有的操作都需要进行计算图的生成#xff08;计算过程的构建#xff0c;以便梯度反向传播等操作#xff09;。而对于tensor的计算操作#xff0c;默认是要进行计算图的构建的#xff0c;在这种情况下#xff0c;可以使用 with torch.n…在使用pytorch时并不是所有的操作都需要进行计算图的生成计算过程的构建以便梯度反向传播等操作。而对于tensor的计算操作默认是要进行计算图的构建的在这种情况下可以使用 with torch.no_grad():强制之后的内容不进行计算图构建。
下面针对是否使用torch.no_grad()做个实验。 1. 不使用torch.no_grad()
import torchx torch.arange(4.0)
x.requires_grad_(True)
# 默认是要进行计算图的构建的
y 2 * torch.dot(x, x)
y.backward()
x.grad
# 输出 tensor([ 0., 4., 8., 12.])2. 使用torch.no_grad()
import torchx torch.arange(4.0)
x.requires_grad_(True)
# 强制之后的内容不进行计算图构建
with torch.no_grad
y 2 * torch.dot(x, x)y.backward()
# 报错 RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn参考资料
https://blog.csdn.net/weixin_44134757/article/details/105775027https://zh-v2.d2l.ai/chapter_preliminaries/autograd.html