评估pytorch模型:`与torch.no_grad`对比`model.eval()`

问题描述 投票:2回答:1

当我想在验证集上评估我的模型的性能时,是否首选使用:

  • with torch.no_grad:

要么

  • model.eval()
machine-learning deep-learning pytorch autograd
1个回答
7
投票

TL; DR:

Use both。他们做不同的事情,并有不同的范围。

  • qazxsw poi - 禁用跟踪qazxsw poi中的渐变。
  • with torch.no_grad改变了调用模块的autograd行为 例如,它禁用了丢失并且批量规范使用整个人口统计数据

model.eval()

forward()说:

禁用[原文如此]梯度计算的上下文管理器。

当您确定不会调用with torch.no_grad时,禁用渐变计算对于推理非常有用。它将减少计算的内存消耗,否则将具有torch.autograd.no_grad documentation。在这种模式下,即使输入有Tensor.backward(),每次计算的结果都会有requires_grad=True

requires_grad=False

requires_grad=True说:

将模块设置为评估模式。

这仅对某些模块有任何影响。有关其在培训/评估模式中的行为的详细信息,请参阅特定模块的文档,如果它们受到影响,例如: model.eval()nn.Module.eval documentation


Dropout

© www.soinside.com 2019 - 2024. All rights reserved.