引言
今天在使用Pytorch導入此前保存的模型進行測試,在過程中發現輸出的結果與驗證結果差距甚大,經過排查后發現是forward與eval()順序問題。
現象
此前的錯誤代碼是
1
2
3
4
5
6
|
input_cpu = torch.ones(( 1 , 2 , 160 , 160 )) target_cpu = torch.ones(( 1 , 2 , 160 , 160 )) target_gpu, input_gpu = target_cpu.cuda(), input_cpu.cuda() model.set_input_2(input_gpu, target_gpu) model. eval () model.forward() |
應該改為
1
2
3
4
5
6
7
|
input_cpu = torch.ones(( 1 , 2 , 160 , 160 )) target_cpu = torch.ones(( 1 , 2 , 160 , 160 )) target_gpu, input_gpu = target_cpu.cuda(), input_cpu.cuda() model.set_input_2(input_gpu, target_gpu) # 先forward再eval model.forward() model. eval () |
當時有個疑慮,為什么要在forward后面再加eval(),查了下相關資料,主要是在BN層以及Dropout的問題。
當使用eval()時,模型會自動固定BN層以及Dropout,選取訓練好的值,否則則會取平均,可能導致生成的圖片顏色失真。
PyTorch進行訓練和測試時一定注意要把實例化的model指定train/eval
使用PyTorch進行訓練和測試時一定注意要把實例化的model指定train/eval,eval()時,框架會自動把BN和DropOut固定住,不會取平均,而是用訓練好的值,不然的話,一旦test的batch_size過小,很容易就會被BN層導致生成圖片顏色失真極大!?。。。?!
eg:
1
2
3
4
5
6
7
8
9
10
|
Class Inpaint_Network() ...... Model = Inpaint_Nerwoek() #train: Model.train(mode = True ) ..... #test: Model. eval () |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_44975887/article/details/103126926