測試代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
import torch import torch.nn as nn m = nn.BatchNorm2d( 2 ,affine = True ) #權重w和偏重將被使用 input = torch.randn( 1 , 2 , 3 , 4 ) output = m( input ) print ( "輸入圖片:" ) print ( input ) print ( "歸一化權重:" ) print (m.weight) print ( "歸一化的偏重:" ) print (m.bias) print ( "歸一化的輸出:" ) print (output) print ( "輸出的尺度:" ) print (output.size()) # i = torch.randn(1,1,2) print ( "輸入的第一個維度:" ) print ( input [ 0 ][ 0 ]) firstDimenMean = torch.Tensor.mean( input [ 0 ][ 0 ]) firstDimenVar = torch.Tensor.var( input [ 0 ][ 0 ], False ) #Bessel's Correction貝塞爾校正不會被使用 print (m.eps) print ( "輸入的第一個維度平均值:" ) print (firstDimenMean) print ( "輸入的第一個維度方差:" ) print (firstDimenVar) bacthnormone = \ (( input [ 0 ][ 0 ][ 0 ][ 0 ] - firstDimenMean) / (torch. pow (firstDimenVar + m.eps, 0.5 ) ))\ * m.weight[ 0 ] + m.bias[ 0 ] print (bacthnormone) |
輸出為:
輸入圖片:
1
2
3
4
5
6
7
8
|
tensor([[[[ - 2.4308 , - 1.0281 , - 1.1322 , 0.9819 ], [ - 0.4069 , 0.7973 , 1.6296 , 1.6797 ], [ 0.2802 , - 0.8285 , 2.0101 , 0.1286 ]], [[ - 0.5740 , 0.1970 , - 0.7209 , - 0.7231 ], [ - 0.1489 , 0.4993 , 0.4159 , 1.4238 ], [ 0.0334 , - 0.6333 , 0.1308 , - 0.2180 ]]]]) |
歸一化權重:
1
2
|
Parameter containing: tensor([ 0.5653 , 0.0322 ]) |
歸一化的偏重:
1
2
|
Parameter containing: tensor([ 0. , 0. ]) |
歸一化的輸出:
1
2
3
4
5
6
7
8
|
tensor([[[[ - 1.1237 , - 0.5106 , - 0.5561 , 0.3679 ], [ - 0.2391 , 0.2873 , 0.6510 , 0.6729 ], [ 0.0612 , - 0.4233 , 0.8173 , - 0.0050 ]], [[ - 0.0293 , 0.0120 , - 0.0372 , - 0.0373 ], [ - 0.0066 , 0.0282 , 0.0237 , 0.0777 ], [ 0.0032 , - 0.0325 , 0.0084 , - 0.0103 ]]]]) |
輸出的尺度:
1
|
torch.Size([ 1 , 2 , 3 , 4 ]) |
輸入的第一個維度:
1
2
3
4
|
tensor([[ - 2.4308 , - 1.0281 , - 1.1322 , 0.9819 ], [ - 0.4069 , 0.7973 , 1.6296 , 1.6797 ], [ 0.2802 , - 0.8285 , 2.0101 , 0.1286 ]]) 1e - 05 |
輸入的第一個維度平均值:
1
|
tensor( 0.1401 ) |
輸入的第一個維度方差:
1
2
|
tensor( 1.6730 ) tensor( - 1.1237 ) |
結論:
輸出的計算公式如下
注意torch中方差實現的方法是沒有使用Bessel's correction 貝塞爾校正的方差,所以在自己寫的方差中不要用錯了。(貝塞爾校正,即樣本方差和總體方差之間區別和校正。)
以上這篇pytorch方法測試詳解——歸一化(BatchNorm2d)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/tmk_01/article/details/80679549