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

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

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