You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

paddle_initializers.py 6.8 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from paddle.fluid.initializer import ConstantInitializer
  4. from paddle.fluid.initializer import UniformInitializer
  5. from paddle.fluid.initializer import NormalInitializer
  6. from paddle.fluid.initializer import TruncatedNormalInitializer
  7. from paddle.fluid.initializer import MSRAInitializer
  8. import paddle
  9. __all__ = [
  10. 'Initializer', 'Zeros', 'Ones', 'Constant', 'RandomUniform', 'RandomNormal', 'TruncatedNormal',
  11. 'deconv2d_bilinear_upsampling_initializer', 'HeNormal'
  12. ]
  13. class Initializer(object):
  14. """Initializer base class: all initializers inherit from this class.
  15. """
  16. def __call__(self, shape, dtype=None):
  17. """Returns a tensor object initialized as specified by the initializer.
  18. Parameters
  19. ----------
  20. shape : tuple of int.
  21. The shape of the tensor.
  22. dtype : Optional dtype of the tensor.
  23. If not provided will return tensor of `tl.float32`.
  24. Returns
  25. -------
  26. """
  27. raise NotImplementedError
  28. def get_config(self):
  29. """Returns the configuration of the initializer as a JSON-serializable dict.
  30. Returns
  31. -------
  32. A JSON-serializable Python dict.
  33. """
  34. return {}
  35. @classmethod
  36. def from_config(cls, config):
  37. """Instantiates an initializer from a configuration dictionary.
  38. Parameters
  39. ----------
  40. config : A python dictionary.
  41. It will typically be the output of `get_config`.
  42. Returns
  43. -------
  44. An Initializer instance.
  45. """
  46. if 'dtype' in config:
  47. config.pop('dtype')
  48. return cls(**config)
  49. class Zeros(ConstantInitializer):
  50. """Initializer that generates tensors initialized to 0.
  51. """
  52. def __init__(self):
  53. super(Zeros, self).__init__(value=0.0, force_cpu=False)
  54. class Ones(object):
  55. """Initializer that generates tensors initialized to 1.
  56. """
  57. def __init__(self):
  58. # super(Ones, self).__init__(value=1.0, force_cpu=False)
  59. pass
  60. def __call__(self, shape, dtype):
  61. return paddle.ones(shape=shape, dtype=dtype)
  62. class Constant(ConstantInitializer):
  63. """Initializer that generates tensors initialized to a constant value.
  64. Parameters
  65. ----------
  66. value : A python scalar or a numpy array.
  67. The assigned value.
  68. """
  69. def __init__(self, value=0.0):
  70. if value is None:
  71. raise ValueError("value must not be none.")
  72. super(Constant, self).__init__(value=value, force_cpu=False)
  73. self.value = value
  74. def get_config(self):
  75. return {"value": self.value}
  76. class RandomUniform(UniformInitializer):
  77. """Initializer that generates tensors with a uniform distribution.
  78. Parameters
  79. ----------
  80. minval : A python scalar or a scalar tensor.
  81. Lower bound of the range of random values to generate.
  82. maxval : A python scalar or a scalar tensor.
  83. Upper bound of the range of random values to generate.
  84. seed : A Python integer.
  85. Used to seed the random generator.
  86. """
  87. def __init__(self, minval=-0.05, maxval=0.05, seed=0):
  88. assert minval is not None, 'low should not be None'
  89. assert maxval is not None, 'high should not be None'
  90. assert maxval >= minval, 'high should greater or equal than low'
  91. super(RandomUniform, self).__init__(low=minval, high=maxval, seed=seed, diag_num=0, diag_step=0, diag_val=1.0)
  92. self.minval = minval
  93. self.maxval = maxval
  94. self.seed = seed
  95. def get_config(self):
  96. return {"minval": self.minval, "maxval": self.maxval, "seed": self.seed}
  97. class RandomNormal(NormalInitializer):
  98. """Initializer that generates tensors with a normal distribution.
  99. Parameters
  100. ----------
  101. mean : A python scalar or a scalar tensor.
  102. Mean of the random values to generate.
  103. stddev : A python scalar or a scalar tensor.
  104. Standard deviation of the random values to generate.
  105. seed : A Python integer.
  106. Used to seed the random generator.
  107. """
  108. def __init__(self, mean=0.0, stddev=0.05, seed=0):
  109. assert mean is not None, 'mean should not be None'
  110. assert stddev is not None, 'std should not be None'
  111. super(RandomNormal, self).__init__(loc=mean, scale=stddev, seed=seed)
  112. self.mean = mean
  113. self.stddev = stddev
  114. self.seed = seed
  115. def get_config(self):
  116. return {"mean": self.mean, "stddev": self.stddev, "seed": self.seed}
  117. class TruncatedNormal(TruncatedNormalInitializer):
  118. """Initializer that generates a truncated normal distribution.
  119. These values are similar to values from a `RandomNormal`
  120. except that values more than two standard deviations from the mean
  121. are discarded and re-drawn. This is the recommended initializer for
  122. neural network weights and filters.
  123. Parameters
  124. ----------
  125. mean : A python scalar or a scalar tensor.
  126. Mean of the random values to generate.
  127. stddev : A python scalar or a scalar tensor.
  128. Standard deviation of the andom values to generate.
  129. seed : A Python integer.
  130. Used to seed the random generator.
  131. """
  132. def __init__(self, mean=0.0, stddev=0.05, seed=0):
  133. assert mean is not None, 'mean should not be None'
  134. assert stddev is not None, 'std should not be None'
  135. super(TruncatedNormal, self).__init__(loc=mean, scale=stddev, seed=seed)
  136. self.mean = mean
  137. self.stddev = stddev
  138. self.seed = seed
  139. def get_config(self):
  140. return {"mean": self.mean, "stddev": self.stddev, "seed": self.seed}
  141. class HeNormal(MSRAInitializer):
  142. """He normal initializer.
  143. Parameters
  144. ----------
  145. seed : A Python integer.
  146. Used to seed the random generator.
  147. """
  148. def __init__(self, seed=0):
  149. super(HeNormal, self).__init__(uniform=False, fan_in=None, seed=seed)
  150. self.seed = seed
  151. def get_config(self):
  152. return {"seed", self.seed}
  153. def deconv2d_bilinear_upsampling_initializer(shape):
  154. """Returns the initializer that can be passed to DeConv2dLayer for initializing the
  155. weights in correspondence to channel-wise bilinear up-sampling.
  156. Used in segmentation approaches such as [FCN](https://arxiv.org/abs/1605.06211)
  157. Parameters
  158. ----------
  159. shape : tuple of int
  160. The shape of the filters, [height, width, output_channels, in_channels].
  161. It must match the shape passed to DeConv2dLayer.
  162. Returns
  163. -------
  164. ``tf.constant_initializer``
  165. A constant initializer with weights set to correspond to per channel bilinear upsampling
  166. when passed as W_int in DeConv2dLayer
  167. """
  168. raise NotImplementedError

TensorLayer3.0 是一款兼容多种深度学习框架为计算后端的深度学习库。计划兼容TensorFlow, Pytorch, MindSpore, Paddle.