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_conv.py 5.7 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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.backend import BACKEND
  7. __all__ = [
  8. 'BinaryConv2d',
  9. ]
  10. class BinaryConv2d(Module):
  11. """
  12. The :class:`BinaryConv2d` class is a 2D binary CNN layer, which weights are either -1 or 1 while inference.
  13. Note that, the bias vector would not be binarized.
  14. Parameters
  15. ----------
  16. n_filter : int
  17. The number of filters.
  18. filter_size : tuple of int
  19. The filter size (height, width).
  20. strides : tuple of int
  21. The sliding window strides of corresponding input dimensions.
  22. It must be in the same order as the ``shape`` parameter.
  23. act : activation function
  24. The activation function of this layer.
  25. padding : str
  26. The padding algorithm type: "SAME" or "VALID".
  27. data_format : str
  28. "channels_last" (NHWC, default) or "channels_first" (NCHW).
  29. dilation_rate : tuple of int
  30. Specifying the dilation rate to use for dilated convolution.
  31. W_init : initializer
  32. The initializer for the the weight matrix.
  33. b_init : initializer or None
  34. The initializer for the the bias vector. If None, skip biases.
  35. in_channels : int
  36. The number of in channels.
  37. name : None or str
  38. A unique layer name.
  39. Examples
  40. ---------
  41. With TensorLayer
  42. >>> net = tl.layers.Input([8, 100, 100, 32], name='input')
  43. >>> binaryconv2d = tl.layers.BinaryConv2d(
  44. ... n_filter=64, filter_size=(3, 3), strides=(2, 2), act=tl.relu, in_channels=32, name='binaryconv2d'
  45. ... )(net)
  46. >>> print(binaryconv2d)
  47. >>> output shape : (8, 50, 50, 64)
  48. """
  49. def __init__(
  50. self, n_filter=32, filter_size=(3, 3), strides=(1, 1), act=None, padding='VALID', data_format="channels_last",
  51. dilation_rate=(1, 1), W_init=tl.initializers.truncated_normal(stddev=0.02),
  52. b_init=tl.initializers.constant(value=0.0), in_channels=None, name=None
  53. ):
  54. super(BinaryConv2d, self).__init__(name, act=act)
  55. self.n_filter = n_filter
  56. self.filter_size = filter_size
  57. self._strides = self.strides = strides
  58. self.padding = padding
  59. self.data_format = data_format
  60. self._dilation_rate = self.dilation_rate = dilation_rate
  61. self.W_init = W_init
  62. self.b_init = b_init
  63. self.in_channels = in_channels
  64. if self.in_channels:
  65. self.build(None)
  66. self._built = True
  67. logging.info(
  68. "BinaryConv2d %s: n_filter: %d filter_size: %s strides: %s pad: %s act: %s" % (
  69. self.name, n_filter, str(filter_size), str(strides), padding,
  70. self.act.__class__.__name__ if self.act is not None else 'No Activation'
  71. )
  72. )
  73. def __repr__(self):
  74. actstr = self.act.__class__.__name__ if self.act is not None else 'No Activation'
  75. s = (
  76. '{classname}(in_channels={in_channels}, out_channels={n_filter}, kernel_size={filter_size}'
  77. ', strides={strides}, padding={padding}'
  78. )
  79. if self.dilation_rate != (1, ) * len(self.dilation_rate):
  80. s += ', dilation={dilation_rate}'
  81. if self.b_init is None:
  82. s += ', bias=False'
  83. s += (', ' + actstr)
  84. if self.name is not None:
  85. s += ', name=\'{name}\''
  86. s += ')'
  87. return s.format(classname=self.__class__.__name__, **self.__dict__)
  88. def build(self, inputs_shape):
  89. if self.data_format == 'channels_last':
  90. self.data_format = 'NHWC'
  91. if self.in_channels is None:
  92. self.in_channels = inputs_shape[-1]
  93. self._strides = [1, self._strides[0], self._strides[1], 1]
  94. self._dilation_rate = [1, self._dilation_rate[0], self._dilation_rate[1], 1]
  95. elif self.data_format == 'channels_first':
  96. self.data_format = 'NCHW'
  97. if self.in_channels is None:
  98. self.in_channels = inputs_shape[1]
  99. self._strides = [1, 1, self._strides[0], self._strides[1]]
  100. self._dilation_rate = [1, 1, self._dilation_rate[0], self._dilation_rate[1]]
  101. else:
  102. raise Exception("data_format should be either channels_last or channels_first")
  103. self.filter_shape = (self.filter_size[0], self.filter_size[1], self.in_channels, self.n_filter)
  104. self.W = self._get_weights("filters", shape=self.filter_shape, init=self.W_init)
  105. self.b_init_flag = False
  106. if self.b_init:
  107. self.b = self._get_weights("biases", shape=(self.n_filter, ), init=self.b_init)
  108. self.bias_add = tl.ops.BiasAdd(self.data_format)
  109. self.b_init_flag = True
  110. self.act_init_flag = False
  111. if self.act:
  112. self.act_init_flag = True
  113. self.binaryconv2d = tl.ops.BinaryConv2D(
  114. strides=self._strides,
  115. padding=self.padding,
  116. data_format=self.data_format,
  117. dilations=self._dilation_rate,
  118. out_channel=self.n_filter,
  119. k_size=self.filter_size,
  120. in_channel=self.in_channels,
  121. )
  122. def forward(self, inputs):
  123. if self._forward_state == False:
  124. if self._built == False:
  125. self.build(tl.get_tensor_shape(inputs))
  126. self._built = True
  127. self._forward_state = True
  128. outputs = self.binaryconv2d(inputs, self.W)
  129. if self.b_init_flag:
  130. outputs = self.bias_add(outputs, self.b)
  131. if self.act_init_flag:
  132. outputs = self.act(outputs)
  133. return outputs

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