pytorch之model.eval()


1.作用

運行model.eval()后批歸一化層和dropout層就不會在推斷時有效果。如果沒有做的話,就會產生不連續的推斷結果。

2.model.eval()和with torch.no_grad()

https://discuss.pytorch.org/t/model-eval-vs-with-torch-no-grad/19615 

https://stackoverflow.com/questions/55627780/evaluating-pytorch-models-with-torch-no-grad-vs-model-eval

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM