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.

separable_conv.py 15 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. 'SeparableConv1d',
  9. 'SeparableConv2d',
  10. ]
  11. class SeparableConv1d(Module):
  12. """The :class:`SeparableConv1d` class is a 1D depthwise separable convolutional layer.
  13. This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels.
  14. Parameters
  15. ------------
  16. n_filter : int
  17. The dimensionality of the output space (i.e. the number of filters in the convolution).
  18. filter_size : int
  19. Specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions.
  20. strides : int
  21. Specifying the stride of the convolution. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1.
  22. act : activation function
  23. The activation function of this layer.
  24. padding : str
  25. One of "valid" or "same" (case-insensitive).
  26. data_format : str
  27. One of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, height, width).
  28. dilation_rate : int
  29. Specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1.
  30. depth_multiplier : int
  31. The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to num_filters_in * depth_multiplier.
  32. depthwise_init : initializer
  33. for the depthwise convolution kernel.
  34. pointwise_init : initializer
  35. For the pointwise convolution kernel.
  36. b_init : initializer
  37. For the bias vector. If None, ignore bias in the pointwise part only.
  38. in_channels : int
  39. The number of in channels.
  40. name : None or str
  41. A unique layer name.
  42. Examples
  43. --------
  44. With TensorLayer
  45. >>> net = tl.layers.Input([8, 50, 64], name='input')
  46. >>> separableconv1d = tl.layers.SeparableConv1d(n_filter=32, filter_size=3, strides=2, padding='SAME', act=tl.ReLU, name='separable_1d')(net)
  47. >>> print(separableconv1d)
  48. >>> output shape : (8, 25, 32)
  49. """
  50. def __init__(
  51. self, n_filter=32, filter_size=1, stride=1, act=None, padding="SAME", data_format="channels_last",
  52. dilation_rate=1, depth_multiplier=1, depthwise_init=tl.initializers.truncated_normal(stddev=0.02),
  53. pointwise_init=tl.initializers.truncated_normal(stddev=0.02), b_init=tl.initializers.constant(value=0.0),
  54. in_channels=None, name=None
  55. ):
  56. super(SeparableConv1d, self).__init__(name, act=act)
  57. self.n_filter = n_filter
  58. self.filter_size = filter_size
  59. self.stride = stride
  60. self.padding = padding
  61. self.data_format = data_format
  62. self.dilation_rate = dilation_rate
  63. self.depth_multiplier = depth_multiplier
  64. self.depthwise_init = depthwise_init
  65. self.pointwise_init = pointwise_init
  66. self.b_init = b_init
  67. self.in_channels = in_channels
  68. if self.in_channels:
  69. self.build(None)
  70. self._built = True
  71. logging.info(
  72. "SeparableConv1d %s: n_filter: %d filter_size: %s strides: %s depth_multiplier: %d act: %s" % (
  73. self.name, n_filter, str(filter_size), str(stride), depth_multiplier,
  74. self.act.__class__.__name__ if self.act is not None else 'No Activation'
  75. )
  76. )
  77. def __repr__(self):
  78. actstr = self.act.__class__.__name__ if self.act is not None else 'No Activation'
  79. s = (
  80. '{classname}(in_channels={in_channels}, out_channels={n_filter}, kernel_size={filter_size}'
  81. ', stride={strides}, padding={padding}'
  82. )
  83. if self.dilation_rate != 1:
  84. s += ', dilation={dilation_rate}'
  85. if self.b_init is None:
  86. s += ', bias=False'
  87. s += (', ' + actstr)
  88. if self.name is not None:
  89. s += ', name=\'{name}\''
  90. s += ')'
  91. return s.format(classname=self.__class__.__name__, **self.__dict__)
  92. def build(self, inputs_shape):
  93. if self.data_format == 'channels_last':
  94. self.data_format = 'NWC'
  95. if self.in_channels is None:
  96. self.in_channels = inputs_shape[-1]
  97. elif self.data_format == 'channels_first':
  98. self.data_format = 'NCW'
  99. if self.in_channels is None:
  100. self.in_channels = inputs_shape[1]
  101. else:
  102. raise Exception("data_format should be either channels_last or channels_first")
  103. if BACKEND == 'tensorflow':
  104. self.depthwise_filter_shape = (self.filter_size, self.in_channels, self.depth_multiplier)
  105. elif BACKEND == 'mindspore':
  106. self.depthwise_filter_shape = (self.filter_size, 1, self.depth_multiplier * self.in_channels)
  107. self.pointwise_filter_shape = (1, self.depth_multiplier * self.in_channels, self.n_filter)
  108. self.depthwise_W = self._get_weights(
  109. 'depthwise_filters', shape=self.depthwise_filter_shape, init=self.depthwise_init
  110. )
  111. self.pointwise_W = self._get_weights(
  112. 'pointwise_filters', shape=self.pointwise_filter_shape, init=self.pointwise_init
  113. )
  114. self.b_init_flag = False
  115. if self.b_init:
  116. self.b = self._get_weights("biases", shape=(self.n_filter, ), init=self.b_init)
  117. self.bias_add = tl.ops.BiasAdd(self.data_format)
  118. self.b_init_flag = True
  119. self.act_init_flag = False
  120. if self.act:
  121. self.activate = self.act
  122. self.act_init_flag = True
  123. self.separable_conv1d = tl.ops.SeparableConv1D(
  124. stride=self.stride, padding=self.padding, data_format=self.data_format, dilations=self.dilation_rate,
  125. out_channel=self.n_filter, k_size=self.filter_size, in_channel=self.in_channels,
  126. depth_multiplier=self.depth_multiplier
  127. )
  128. def forward(self, inputs):
  129. if self._forward_state == False:
  130. if self._built == False:
  131. self.build(tl.get_tensor_shape(inputs))
  132. self._built = True
  133. self._forward_state = True
  134. outputs = self.separable_conv1d(inputs, self.depthwise_W, self.pointwise_W)
  135. if self.b_init_flag:
  136. outputs = self.bias_add(outputs, self.b)
  137. if self.act_init_flag:
  138. outputs = self.act(outputs)
  139. return outputs
  140. class SeparableConv2d(Module):
  141. """The :class:`SeparableConv2d` class is a 2D depthwise separable convolutional layer.
  142. This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels.
  143. Parameters
  144. ------------
  145. n_filter : int
  146. The dimensionality of the output space (i.e. the number of filters in the convolution).
  147. filter_size : tuple of int
  148. Specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions.
  149. strides : tuple of int
  150. Specifying the stride of the convolution. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1.
  151. act : activation function
  152. The activation function of this layer.
  153. padding : str
  154. One of "valid" or "same" (case-insensitive).
  155. data_format : str
  156. One of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, height, width).
  157. dilation_rate : tuple of int
  158. Specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1.
  159. depth_multiplier : int
  160. The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to num_filters_in * depth_multiplier.
  161. depthwise_init : initializer
  162. for the depthwise convolution kernel.
  163. pointwise_init : initializer
  164. For the pointwise convolution kernel.
  165. b_init : initializer
  166. For the bias vector. If None, ignore bias in the pointwise part only.
  167. in_channels : int
  168. The number of in channels.
  169. name : None or str
  170. A unique layer name.
  171. Examples
  172. --------
  173. With TensorLayer
  174. >>> net = tl.layers.Input([8, 50, 50, 64], name='input')
  175. >>> separableconv2d = tl.layers.SeparableConv2d(n_filter=32, filter_size=3, strides=2, depth_multiplier = 3 , padding='SAME', act=tl.ReLU, name='separable_2d')(net)
  176. >>> print(separableconv2d)
  177. >>> output shape : (8, 24, 24, 32)
  178. """
  179. def __init__(
  180. self, n_filter=32, filter_size=(1, 1), strides=(1, 1), act=None, padding="VALID", data_format="channels_last",
  181. dilation_rate=(1, 1), depth_multiplier=1, depthwise_init=tl.initializers.truncated_normal(stddev=0.02),
  182. pointwise_init=tl.initializers.truncated_normal(stddev=0.02), b_init=tl.initializers.constant(value=0.0),
  183. in_channels=None, name=None
  184. ):
  185. super(SeparableConv2d, self).__init__(name, act=act)
  186. self.n_filter = n_filter
  187. self.filter_size = filter_size
  188. self._strides = self.strides = strides
  189. self.padding = padding
  190. self.data_format = data_format
  191. self._dilation_rate = self.dilation_rate = dilation_rate
  192. self.depth_multiplier = depth_multiplier
  193. self.depthwise_init = depthwise_init
  194. self.pointwise_init = pointwise_init
  195. self.b_init = b_init
  196. self.in_channels = in_channels
  197. if self.in_channels:
  198. self.build(None)
  199. self._built = True
  200. logging.info(
  201. "SeparableConv2d %s: n_filter: %d filter_size: %s strides: %s depth_multiplier: %d act: %s" % (
  202. self.name, n_filter, str(filter_size), str(strides), depth_multiplier,
  203. self.act.__class__.__name__ if self.act is not None else 'No Activation'
  204. )
  205. )
  206. def __repr__(self):
  207. actstr = self.act.__class__.__name__ if self.act is not None else 'No Activation'
  208. s = (
  209. '{classname}(in_channels={in_channels}, out_channels={n_filter}, kernel_size={filter_size}'
  210. ', stride={strides }, padding={padding}'
  211. )
  212. if self.dilation_rate != (1, ) * len(self.dilation_rate):
  213. s += ', dilation={dilation_rate}'
  214. if self.b_init is None:
  215. s += ', bias=False'
  216. s += (', ' + actstr)
  217. if self.name is not None:
  218. s += ', name=\'{name}\''
  219. s += ')'
  220. return s.format(classname=self.__class__.__name__, **self.__dict__)
  221. def build(self, inputs_shape):
  222. if self.data_format == 'channels_last':
  223. self.data_format = 'NHWC'
  224. if self.in_channels is None:
  225. self.in_channels = inputs_shape[-1]
  226. self._strides = [1, self._strides[0], self._strides[1], 1]
  227. self._dilation_rate = [1, self._dilation_rate[0], self._dilation_rate[1], 1]
  228. elif self.data_format == 'channels_first':
  229. self.data_format = 'NCHW'
  230. if self.in_channels is None:
  231. self.in_channels = inputs_shape[1]
  232. self._strides = [1, 1, self._strides[0], self._strides[1]]
  233. self._dilation_rate = [1, 1, self._dilation_rate[0], self._dilation_rate[1]]
  234. else:
  235. raise Exception("data_format should be either channels_last or channels_first")
  236. if BACKEND == 'tensorflow':
  237. self.depthwise_filter_shape = (
  238. self.filter_size[0], self.filter_size[1], self.in_channels, self.depth_multiplier
  239. )
  240. self.pointwise_filter_shape = (1, 1, self.depth_multiplier * self.in_channels, self.n_filter)
  241. elif BACKEND == 'mindspore':
  242. self.depthwise_filter_shape = (
  243. self.filter_size[0], self.filter_size[1], 1, self.depth_multiplier * self.in_channels
  244. )
  245. self.pointwise_filter_shape = (1, 1, self.depth_multiplier * self.in_channels, self.n_filter)
  246. self.depthwise_W = self._get_weights(
  247. 'depthwise_filters', shape=self.depthwise_filter_shape, init=self.depthwise_init
  248. )
  249. self.pointwise_W = self._get_weights(
  250. 'pointwise_filters', shape=self.pointwise_filter_shape, init=self.pointwise_init
  251. )
  252. self.b_init_flag = False
  253. if self.b_init:
  254. self.b = self._get_weights("biases", shape=(self.n_filter, ), init=self.b_init)
  255. self.bias_add = tl.ops.BiasAdd(self.data_format)
  256. self.b_init_flag = True
  257. self.act_init_flag = False
  258. if self.act:
  259. self.act_init_flag = True
  260. self.separable_conv2d = tl.ops.SeparableConv2D(
  261. strides=self._strides, padding=self.padding, data_format=self.data_format, dilations=self._dilation_rate,
  262. out_channel=self.n_filter, k_size=self.filter_size, in_channel=self.in_channels,
  263. depth_multiplier=self.depth_multiplier
  264. )
  265. def forward(self, inputs):
  266. if self._forward_state == False:
  267. if self._built == False:
  268. self.build(tl.get_tensor_shape(inputs))
  269. self._built = True
  270. self._forward_state = True
  271. outputs = self.separable_conv2d(inputs, self.depthwise_W, self.pointwise_W)
  272. if self.b_init_flag:
  273. outputs = self.bias_add(outputs, self.b)
  274. if self.act_init_flag:
  275. outputs = self.act(outputs)
  276. return outputs

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