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.

binary_dense.py 3.6 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import tensorlayer as tl
  4. from tensorlayer import logging
  5. from tensorlayer.layers.core import Module
  6. from tensorlayer.layers.utils import quantize
  7. __all__ = [
  8. 'BinaryDense',
  9. ]
  10. class BinaryDense(Module):
  11. """The :class:`BinaryDense` class is a binary fully connected layer, which weights are either -1 or 1 while inferencing.
  12. Note that, the bias vector would not be binarized.
  13. Parameters
  14. ----------
  15. n_units : int
  16. The number of units of this layer.
  17. act : activation function
  18. The activation function of this layer, usually set to ``tf.act.sign`` or apply :class:`Sign` after :class:`BatchNorm`.
  19. use_gemm : boolean
  20. If True, use gemm instead of ``tf.matmul`` for inference. (TODO).
  21. W_init : initializer
  22. The initializer for the weight matrix.
  23. b_init : initializer or None
  24. The initializer for the bias vector. If None, skip biases.
  25. in_channels: int
  26. The number of channels of the previous layer.
  27. If None, it will be automatically detected when the layer is forwarded for the first time.
  28. name : None or str
  29. A unique layer name.
  30. """
  31. def __init__(
  32. self,
  33. n_units=100,
  34. act=None,
  35. use_gemm=False,
  36. W_init=tl.initializers.truncated_normal(stddev=0.05),
  37. b_init=tl.initializers.constant(value=0.0),
  38. in_channels=None,
  39. name=None,
  40. ):
  41. super().__init__(name, act=act)
  42. self.n_units = n_units
  43. self.use_gemm = use_gemm
  44. self.W_init = W_init
  45. self.b_init = b_init
  46. self.in_channels = in_channels
  47. if self.in_channels is not None:
  48. self.build((None, self.in_channels))
  49. self._built = True
  50. logging.info(
  51. "BinaryDense %s: %d %s" %
  52. (self.name, n_units, self.act.__class__.__name__ if self.act is not None else 'No Activation')
  53. )
  54. def __repr__(self):
  55. actstr = self.act.__class__.__name__ if self.act is not None else 'No Activation'
  56. s = ('{classname}(n_units={n_units}, ' + actstr)
  57. if self.in_channels is not None:
  58. s += ', in_channels=\'{in_channels}\''
  59. if self.name is not None:
  60. s += ', name=\'{name}\''
  61. s += ')'
  62. return s.format(classname=self.__class__.__name__, **self.__dict__)
  63. def build(self, inputs_shape):
  64. if len(inputs_shape) != 2:
  65. raise Exception("The input dimension must be rank 2, please reshape or flatten it")
  66. if self.in_channels is None:
  67. self.in_channels = inputs_shape[1]
  68. if self.use_gemm:
  69. raise Exception("TODO. The current version use tf.matmul for inferencing.")
  70. n_in = inputs_shape[-1]
  71. self.W = self._get_weights("weights", shape=(n_in, self.n_units), init=self.W_init)
  72. if self.b_init is not None:
  73. self.b = self._get_weights("biases", shape=(self.n_units), init=self.b_init)
  74. self.bias_add = tl.ops.BiasAdd()
  75. self.matmul = tl.ops.MatMul()
  76. def forward(self, inputs):
  77. if self._forward_state == False:
  78. if self._built == False:
  79. self.build(tl.get_tensor_shape(inputs))
  80. self._built = True
  81. self._forward_state = True
  82. W_ = quantize(self.W)
  83. outputs = self.matmul(inputs, W_)
  84. if self.b_init is not None:
  85. outputs = self.bias_add(outputs, self.b)
  86. if self.act:
  87. outputs = self.act(outputs)
  88. return outputs

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