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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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=tf.nn.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. self.pointwise_filter_shape = (1, self.depth_multiplier * self.in_channels, self.n_filter)
  106. elif BACKEND == 'mindspore':
  107. self.depthwise_filter_shape = (self.filter_size, 1, self.depth_multiplier * self.in_channels)
  108. self.pointwise_filter_shape = (1, self.depth_multiplier * self.in_channels, self.n_filter)
  109. self.depthwise_W = self._get_weights(
  110. 'depthwise_filters', shape=self.depthwise_filter_shape, init=self.depthwise_init
  111. )
  112. self.pointwise_W = self._get_weights(
  113. 'pointwise_filters', shape=self.pointwise_filter_shape, init=self.pointwise_init
  114. )
  115. self.b_init_flag = False
  116. if self.b_init:
  117. self.b = self._get_weights("biases", shape=(self.n_filter, ), init=self.b_init)
  118. self.bias_add = tl.ops.BiasAdd(self.data_format)
  119. self.b_init_flag = True
  120. self.act_init_flag = False
  121. if self.act:
  122. self.activate = self.act
  123. self.act_init_flag = True
  124. self.separable_conv1d = tl.ops.SeparableConv1D(
  125. stride=self.stride, padding=self.padding, data_format=self.data_format, dilations=self.dilation_rate,
  126. out_channel=self.n_filter, k_size=self.filter_size, in_channel=self.in_channels,
  127. depth_multiplier=self.depth_multiplier
  128. )
  129. def forward(self, inputs):
  130. if self._forward_state == False:
  131. if self._built == False:
  132. self.build(tl.get_tensor_shape(inputs))
  133. self._built = True
  134. self._forward_state = True
  135. outputs = self.separable_conv1d(inputs, self.depthwise_W, self.pointwise_W)
  136. if self.b_init_flag:
  137. outputs = self.bias_add(outputs, self.b)
  138. if self.act_init_flag:
  139. outputs = self.act(outputs)
  140. return outputs
  141. class SeparableConv2d(Module):
  142. """The :class:`SeparableConv2d` class is a 2D depthwise separable convolutional layer.
  143. This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels.
  144. Parameters
  145. ------------
  146. n_filter : int
  147. The dimensionality of the output space (i.e. the number of filters in the convolution).
  148. filter_size : tuple of int
  149. Specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions.
  150. strides : tuple of int
  151. 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.
  152. act : activation function
  153. The activation function of this layer.
  154. padding : str
  155. One of "valid" or "same" (case-insensitive).
  156. data_format : str
  157. 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).
  158. dilation_rate : tuple of int
  159. 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.
  160. depth_multiplier : int
  161. 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.
  162. depthwise_init : initializer
  163. for the depthwise convolution kernel.
  164. pointwise_init : initializer
  165. For the pointwise convolution kernel.
  166. b_init : initializer
  167. For the bias vector. If None, ignore bias in the pointwise part only.
  168. in_channels : int
  169. The number of in channels.
  170. name : None or str
  171. A unique layer name.
  172. Examples
  173. --------
  174. With TensorLayer
  175. >>> net = tl.layers.Input([8, 50, 50, 64], name='input')
  176. >>> separableconv2d = tl.layers.SeparableConv2d(n_filter=32, filter_size=3, strides=2, depth_multiplier = 3 , padding='SAME', act=tf.nn.relu, name='separable_2d')(net)
  177. >>> print(separableconv2d)
  178. >>> output shape : (8, 24, 24, 32)
  179. """
  180. def __init__(
  181. self, n_filter=32, filter_size=(1, 1), strides=(1, 1), act=None, padding="VALID", data_format="channels_last",
  182. dilation_rate=(1, 1), depth_multiplier=1, depthwise_init=tl.initializers.truncated_normal(stddev=0.02),
  183. pointwise_init=tl.initializers.truncated_normal(stddev=0.02), b_init=tl.initializers.constant(value=0.0),
  184. in_channels=None, name=None
  185. ):
  186. super(SeparableConv2d, self).__init__(name, act=act)
  187. self.n_filter = n_filter
  188. self.filter_size = filter_size
  189. self._strides = self.strides = strides
  190. self.padding = padding
  191. self.data_format = data_format
  192. self._dilation_rate = self.dilation_rate = dilation_rate
  193. self.depth_multiplier = depth_multiplier
  194. self.depthwise_init = depthwise_init
  195. self.pointwise_init = pointwise_init
  196. self.b_init = b_init
  197. self.in_channels = in_channels
  198. if self.in_channels:
  199. self.build(None)
  200. self._built = True
  201. logging.info(
  202. "SeparableConv2d %s: n_filter: %d filter_size: %s strides: %s depth_multiplier: %d act: %s" % (
  203. self.name, n_filter, str(filter_size), str(strides), depth_multiplier,
  204. self.act.__class__.__name__ if self.act is not None else 'No Activation'
  205. )
  206. )
  207. def __repr__(self):
  208. actstr = self.act.__class__.__name__ if self.act is not None else 'No Activation'
  209. s = (
  210. '{classname}(in_channels={in_channels}, out_channels={n_filter}, kernel_size={filter_size}'
  211. ', stride={strides }, padding={padding}'
  212. )
  213. if self.dilation_rate != (1, ) * len(self.dilation_rate):
  214. s += ', dilation={dilation_rate}'
  215. if self.b_init is None:
  216. s += ', bias=False'
  217. s += (', ' + actstr)
  218. if self.name is not None:
  219. s += ', name=\'{name}\''
  220. s += ')'
  221. return s.format(classname=self.__class__.__name__, **self.__dict__)
  222. def build(self, inputs_shape):
  223. if self.data_format == 'channels_last':
  224. self.data_format = 'NHWC'
  225. if self.in_channels is None:
  226. self.in_channels = inputs_shape[-1]
  227. self._strides = [1, self._strides[0], self._strides[1], 1]
  228. self._dilation_rate = [1, self._dilation_rate[0], self._dilation_rate[1], 1]
  229. elif self.data_format == 'channels_first':
  230. self.data_format = 'NCHW'
  231. if self.in_channels is None:
  232. self.in_channels = inputs_shape[1]
  233. self._strides = [1, 1, self._strides[0], self._strides[1]]
  234. self._dilation_rate = [1, 1, self._dilation_rate[0], self._dilation_rate[1]]
  235. else:
  236. raise Exception("data_format should be either channels_last or channels_first")
  237. if BACKEND == 'tensorflow':
  238. self.depthwise_filter_shape = (
  239. self.filter_size[0], self.filter_size[1], self.in_channels, self.depth_multiplier
  240. )
  241. self.pointwise_filter_shape = (1, 1, self.depth_multiplier * self.in_channels, self.n_filter)
  242. elif BACKEND == 'mindspore':
  243. self.depthwise_filter_shape = (
  244. self.filter_size[0], self.filter_size[1], 1, self.depth_multiplier * self.in_channels
  245. )
  246. self.pointwise_filter_shape = (1, 1, self.depth_multiplier * self.in_channels, self.n_filter)
  247. self.depthwise_W = self._get_weights(
  248. 'depthwise_filters', shape=self.depthwise_filter_shape, init=self.depthwise_init
  249. )
  250. self.pointwise_W = self._get_weights(
  251. 'pointwise_filters', shape=self.pointwise_filter_shape, init=self.pointwise_init
  252. )
  253. self.b_init_flag = False
  254. if self.b_init:
  255. self.b = self._get_weights("biases", shape=(self.n_filter, ), init=self.b_init)
  256. self.bias_add = tl.ops.BiasAdd(self.data_format)
  257. self.b_init_flag = True
  258. self.act_init_flag = False
  259. if self.act:
  260. self.act_init_flag = True
  261. self.separable_conv2d = tl.ops.SeparableConv2D(
  262. strides=self._strides, padding=self.padding, data_format=self.data_format, dilations=self._dilation_rate,
  263. out_channel=self.n_filter, k_size=self.filter_size, in_channel=self.in_channels,
  264. depth_multiplier=self.depth_multiplier
  265. )
  266. def forward(self, inputs):
  267. if self._forward_state == False:
  268. if self._built == False:
  269. self.build(tl.get_tensor_shape(inputs))
  270. self._built = True
  271. self._forward_state = True
  272. outputs = self.separable_conv2d(inputs, self.depthwise_W, self.pointwise_W)
  273. if self.b_init_flag:
  274. outputs = self.bias_add(outputs, self.b)
  275. if self.act_init_flag:
  276. outputs = self.act(outputs)
  277. return outputs
  278. if __name__ == '__main__':
  279. net = tl.layers.Input([5, 400, 400, 3], name='input')
  280. layer = SeparableConv2d(
  281. in_channels=3, filter_size=(3, 3), strides=(2, 2), dilation_rate=(2, 2), act=tl.ReLU, depth_multiplier=3,
  282. name='separableconv2d1'
  283. )
  284. print(len(layer.all_weights))
  285. print(layer(net).shape)

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