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.

group_conv.py 6.5 kB

4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. 'GroupConv2d',
  9. ]
  10. class GroupConv2d(Module):
  11. """The :class:`GroupConv2d` class is 2D grouped convolution, see `here <https://blog.yani.io/filter-group-tutorial/>`__.
  12. Parameters
  13. --------------
  14. n_filter : int
  15. The number of filters.
  16. filter_size : tuple of int
  17. The filter size.
  18. stride : tuple of int
  19. The stride step.
  20. n_group : int
  21. The number of groups.
  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 weight matrix.
  32. b_init : initializer or None
  33. The initializer for 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, 24, 24, 32], name='input')
  42. >>> groupconv2d = tl.layers.QuanConv2d(
  43. ... n_filter=64, filter_size=(3, 3), strides=(2, 2), n_group=2, name='group'
  44. ... )(net)
  45. >>> print(groupconv2d)
  46. >>> output shape : (8, 12, 12, 64)
  47. """
  48. def __init__(
  49. self, n_filter=32, filter_size=(1, 1), strides=(1, 1), n_group=1, act=None, padding='SAME',
  50. data_format="channels_last", dilation_rate=(1, 1), W_init=tl.initializers.truncated_normal(stddev=0.02),
  51. b_init=tl.initializers.constant(value=0.0), in_channels=None, name=None
  52. ):
  53. super().__init__(name, act=act)
  54. self.n_filter = n_filter
  55. self.filter_size = filter_size
  56. self._strides = self.strides = strides
  57. self.n_group = n_group
  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. "Conv2d %s: n_filter: %d filter_size: %s strides: %s n_group: %d pad: %s act: %s" % (
  69. self.name, n_filter, str(filter_size), str(strides), n_group, 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}, n_group = {n_group}, 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. if self.n_group < 1:
  104. raise ValueError(
  105. "The n_group must be a integer greater than or equal to 1, but we got :{}".format(self.n_group)
  106. )
  107. if self.in_channels % self.n_group != 0:
  108. raise ValueError(
  109. "The channels of input must be divisible by n_group, but we got: the channels of input"
  110. "is {}, the n_group is {}.".format(self.in_channels, self.n_group)
  111. )
  112. if self.n_filter % self.n_group != 0:
  113. raise ValueError(
  114. "The number of filters must be divisible by n_group, but we got: the number of filters "
  115. "is {}, the n_group is {}. ".format(self.n_filter, self.n_group)
  116. )
  117. # TODO channels first filter shape [out_channel, in_channel/n_group, filter_h, filter_w]
  118. self.filter_shape = (
  119. self.filter_size[0], self.filter_size[1], int(self.in_channels / self.n_group), self.n_filter
  120. )
  121. self.W = self._get_weights("filters", shape=self.filter_shape, init=self.W_init)
  122. self.b_init_flag = False
  123. if self.b_init:
  124. self.b = self._get_weights("biases", shape=(self.n_filter, ), init=self.b_init)
  125. self.bias_add = tl.ops.BiasAdd(self.data_format)
  126. self.b_init_flag = True
  127. self.group_conv2d = tl.ops.GroupConv2D(
  128. strides=self._strides, padding=self.padding, data_format=self.data_format, dilations=self._dilation_rate,
  129. out_channel=self.n_filter, k_size=(self.filter_size[0], self.filter_size[1]), groups=self.n_group
  130. )
  131. self.act_init_flag = False
  132. if self.act:
  133. self.act_init_flag = True
  134. def forward(self, inputs):
  135. if self._forward_state == False:
  136. if self._built == False:
  137. self.build(tl.get_tensor_shape(inputs))
  138. self._built = True
  139. self._forward_state = True
  140. outputs = self.group_conv2d(inputs, self.W)
  141. if self.b_init_flag:
  142. outputs = self.bias_add(outputs, self.b)
  143. if self.act_init_flag:
  144. outputs = self.act(outputs)
  145. return outputs

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