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.9 kB

4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. Examples
  31. --------
  32. >>> net = tl.layers.Input([10, 784], name='input')
  33. >>> net = tl.layers.BinaryDense(n_units=800, act=tl.ReLU, name='relu1')(net)
  34. >>> output shape :(10, 800)
  35. >>> net = tl.layers.BinaryDense(n_units=10, name='output')(net)
  36. >>> output shape : (10, 10)
  37. """
  38. def __init__(
  39. self,
  40. n_units=100,
  41. act=None,
  42. use_gemm=False,
  43. W_init=tl.initializers.truncated_normal(stddev=0.05),
  44. b_init=tl.initializers.constant(value=0.0),
  45. in_channels=None,
  46. name=None,
  47. ):
  48. super().__init__(name, act=act)
  49. self.n_units = n_units
  50. self.use_gemm = use_gemm
  51. self.W_init = W_init
  52. self.b_init = b_init
  53. self.in_channels = in_channels
  54. if self.in_channels is not None:
  55. self.build((None, self.in_channels))
  56. self._built = True
  57. logging.info(
  58. "BinaryDense %s: %d %s" %
  59. (self.name, n_units, self.act.__class__.__name__ if self.act is not None else 'No Activation')
  60. )
  61. def __repr__(self):
  62. actstr = self.act.__class__.__name__ if self.act is not None else 'No Activation'
  63. s = ('{classname}(n_units={n_units}, ' + actstr)
  64. if self.in_channels is not None:
  65. s += ', in_channels=\'{in_channels}\''
  66. if self.name is not None:
  67. s += ', name=\'{name}\''
  68. s += ')'
  69. return s.format(classname=self.__class__.__name__, **self.__dict__)
  70. def build(self, inputs_shape):
  71. if len(inputs_shape) != 2:
  72. raise Exception("The input dimension must be rank 2, please reshape or flatten it")
  73. if self.in_channels is None:
  74. self.in_channels = inputs_shape[1]
  75. if self.use_gemm:
  76. raise Exception("TODO. The current version use tf.matmul for inferencing.")
  77. n_in = inputs_shape[-1]
  78. self.W = self._get_weights("weights", shape=(n_in, self.n_units), init=self.W_init)
  79. if self.b_init is not None:
  80. self.b = self._get_weights("biases", shape=(self.n_units), init=self.b_init)
  81. self.bias_add = tl.ops.BiasAdd()
  82. self.matmul = tl.ops.MatMul()
  83. def forward(self, inputs):
  84. if self._forward_state == False:
  85. if self._built == False:
  86. self.build(tl.get_tensor_shape(inputs))
  87. self._built = True
  88. self._forward_state = True
  89. W_ = quantize(self.W)
  90. outputs = self.matmul(inputs, W_)
  91. if self.b_init is not None:
  92. outputs = self.bias_add(outputs, self.b)
  93. if self.act:
  94. outputs = self.act(outputs)
  95. return outputs

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