1.作用
运行model.eval()后批归一化层和dropout层就不会在推断时有效果。如果没有做的话,就会产生不连续的推断结果。
2.model.eval()和with torch.no_grad()
https://discuss.pytorch.org/t/model-eval-vs-with-torch-no-grad/19615
- model.eval():使得所有层进入评估模式,并且 batchnorm or dropout层都会是评估模式(禁用dropout),而不是训练模式;主要关注forward()函数中的行为。This has any effect only on certain modules.
- torch.no_grad():停止计算梯度,不能进行反向传播。In this mode, the result of every computation will have
requires_grad=False
, even when the inputs haverequires_grad=True
.
所以在使用时两个一起用,作用不同。
https://pytorch-cn.readthedocs.io/zh/latest/package_references/torch-nn/ 下面这个是中文官方教程里的说法。
知乎 https://www.zhihu.com/question/363144860/answer/951669576
上述回答中提到在train/predict中批归一化层与dropout计算的区别:
https://blog.csdn.net/Charles5101/article/details/106148441/
- model.eval():
import torch import torch.nn as nn drop = nn.Dropout() x = torch.ones(10) # Train mode drop.train() print(drop(x)) # tensor([2., 2., 0., 2., 2., 2., 2., 0., 0., 2.]) # Eval mode drop.eval() print(drop(x)) # tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
在train和eval模式下,dropout层进行forward的区别。
- torch.no_grad() 负责关掉梯度计算,节省eval的时间。