Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

BatchNorm2D.py 1.6 KB

You have to be logged in to leave a comment. Sign In
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
37
38
39
40
41
42
  1. from core.leras import nn
  2. tf = nn.tf
  3. class BatchNorm2D(nn.LayerBase):
  4. """
  5. currently not for training
  6. """
  7. def __init__(self, dim, eps=1e-05, momentum=0.1, dtype=None, **kwargs):
  8. self.dim = dim
  9. self.eps = eps
  10. self.momentum = momentum
  11. if dtype is None:
  12. dtype = nn.floatx
  13. self.dtype = dtype
  14. super().__init__(**kwargs)
  15. def build_weights(self):
  16. self.weight = tf.get_variable("weight", (self.dim,), dtype=self.dtype, initializer=tf.initializers.ones() )
  17. self.bias = tf.get_variable("bias", (self.dim,), dtype=self.dtype, initializer=tf.initializers.zeros() )
  18. self.running_mean = tf.get_variable("running_mean", (self.dim,), dtype=self.dtype, initializer=tf.initializers.zeros(), trainable=False )
  19. self.running_var = tf.get_variable("running_var", (self.dim,), dtype=self.dtype, initializer=tf.initializers.zeros(), trainable=False )
  20. def get_weights(self):
  21. return [self.weight, self.bias, self.running_mean, self.running_var]
  22. def forward(self, x):
  23. if nn.data_format == "NHWC":
  24. shape = (1,1,1,self.dim)
  25. else:
  26. shape = (1,self.dim,1,1)
  27. weight = tf.reshape ( self.weight , shape )
  28. bias = tf.reshape ( self.bias , shape )
  29. running_mean = tf.reshape ( self.running_mean, shape )
  30. running_var = tf.reshape ( self.running_var , shape )
  31. x = (x - running_mean) / tf.sqrt( running_var + self.eps )
  32. x *= weight
  33. x += bias
  34. return x
  35. nn.BatchNorm2D = BatchNorm2D
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...