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的時間。
