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.

vm_me.py 26 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """VM implementations based on numpy."""
  16. import numpy as np
  17. from mindspore._checkparam import Rel
  18. from mindspore._checkparam import Validator as validator
  19. def avg_pooling(x, pool_h, pool_w, stride):
  20. """
  21. Applies average pooling over an input array.
  22. Args:
  23. x (numpy.ndarray): The input array to be average pooled.
  24. pool_h (int): Height of the pooling window.
  25. pool_w (int): Width of the pooling window.
  26. stride (int): The stride of the sliding window.
  27. Returns:
  28. numpy.ndarray, an output array after applying average pooling on input array.
  29. """
  30. validator.check_integer("stride", stride, 0, Rel.GT, None)
  31. num, channel, height, width = x.shape
  32. out_h = (height - pool_h) // stride + 1
  33. out_w = (width - pool_w) // stride + 1
  34. col = im2col(x, pool_h, pool_w, stride)
  35. col = col.reshape(-1, pool_h * pool_w)
  36. out = np.mean(col, axis=1)
  37. out = out.reshape((num, out_h, out_w, channel)).transpose(0, 3, 1, 2)
  38. return out
  39. def avg_pool_grad(dout, origin_shape, pool_h, pool_w, stride):
  40. """
  41. Gets grad of average pooling.
  42. Args:
  43. x (numpy.ndarray): The input array to be average pooled.
  44. dout (numpy.ndarray): The grad of pre-layer.
  45. pool_h (int): Height of the pooling window.
  46. pool_w (int): Width of the pooling window.
  47. stride (int): The stride of the sliding window.
  48. Returns:
  49. numpy.ndarray, grad of avgerage pooling.
  50. """
  51. # pylint: disable=unused-argument
  52. _, _, height, width = dout.shape
  53. dx = np.zeros(origin_shape)
  54. for i in range(height):
  55. for j in range(width):
  56. dx[:, :, i:(i + pool_h), j:(j + pool_w)] += np.ones((pool_h, pool_w))
  57. return dx
  58. def _batch_norm(x, scale, shift, running_mean=None, running_var=None,
  59. eps=1e-05, momentum=0.1, is_training=True):
  60. """Batch normalization over an array."""
  61. _, c_h_w = x.shape
  62. # Handle running_mean and running_var are not None
  63. # if running_mean is None:
  64. # running_mean = np.zeros(c_h_w)
  65. # running_var = np.zeros(c_h_w)
  66. running_mean = np.zeros(c_h_w)
  67. running_var = np.zeros(c_h_w)
  68. if np.ndim(scale) > 0:
  69. scale = scale.mean()
  70. if np.ndim(shift) > 0:
  71. shift = shift.mean()
  72. if is_training:
  73. x_mean = np.mean(x, axis=0)
  74. x_var = np.var(x, axis=0)
  75. # Normalization followed by Affine transformation
  76. x_norm = (x - x_mean) / np.sqrt(x_var + eps)
  77. # Estimate running average of mean and variance to use at test time
  78. running_mean = momentum * running_mean + (1 - momentum) * x_mean
  79. running_var = momentum * running_var + (1 - momentum) * x_var
  80. else:
  81. # normalize using running average
  82. x_norm = (x - running_mean) / np.sqrt(running_var + eps)
  83. x_mean = running_mean
  84. x_var = running_var
  85. out = scale * x_norm + shift
  86. return out, x_mean, x_var, running_mean, running_var
  87. def batch_norm(x, scale=1, shift=0, mean=None, variance=None,
  88. eps=1e-05, momentum=0.1, is_training=True):
  89. """Batch normalization over an array."""
  90. input_shape = x.shape
  91. if x.ndim != 2:
  92. batch_num = x.shape[0]
  93. x = x.reshape(batch_num, -1)
  94. out, _, _, running_mean, running_var = _batch_norm(x, scale, shift, mean, variance, \
  95. eps, momentum, is_training)
  96. return out.reshape(*input_shape), np.array(scale), np.array(shift), running_mean, running_var
  97. def _batch_norm_grad(dout, x, scale, save_mean, save_inv_variance, \
  98. eps=1e-05, momentum=0.1, is_training=True):
  99. """Batch normalization over an array."""
  100. if x.ndim != 2:
  101. batch_num = x.shape[0]
  102. x = x.reshape(batch_num, -1)
  103. if np.ndim(scale) > 0:
  104. scale = scale.mean()
  105. x_norm, x_mean, x_var, _, _ = _batch_norm(x, scale, shift=0, running_mean=save_mean, \
  106. running_var=save_inv_variance, \
  107. eps=eps, momentum=momentum, is_training=is_training)
  108. batch_size = x.shape[0]
  109. dx_norm = scale * dout
  110. dvar = np.sum(dx_norm * (x - x_mean) * ((x_var + eps) ** (-3.0 / 2)) * (-1.0 / 2), axis=0)
  111. dmean = np.sum(dx_norm * (-1.0 / np.sqrt(x_var + eps)), axis=0) \
  112. + dvar * (np.sum(-2 * (x - x_mean), axis=0) * (1.0 / batch_size))
  113. dx = dx_norm * (1.0 / np.sqrt(x_var + eps)) + dvar * (2.0 * (x - x_mean) / batch_size) + dmean * (1.0 / batch_size)
  114. dgamma = np.sum(dout * x_norm, axis=0)
  115. dbeta = np.sum(dout, axis=0)
  116. return dx, dgamma, dbeta
  117. def batch_norm_grad(dy, x, scale, save_mean, save_inv_variance):
  118. """Batch normalization over an array."""
  119. if dy.ndim != 2:
  120. batch_size = dy.shape[0]
  121. dy = dy.reshape(batch_size, -1)
  122. dx, dgamma, dbeta = _batch_norm_grad(dy, x, scale, save_mean, save_inv_variance)
  123. input_shape = x.shape
  124. dx = dx.reshape(*input_shape)
  125. return dx, dgamma, dbeta
  126. def col2im(col, input_shape, filter_h, filter_w, stride=1, pad=0):
  127. """Rearranges a row vector to an image."""
  128. if isinstance(stride, int):
  129. stride_h = stride
  130. stride_w = stride
  131. elif isinstance(stride, tuple) and len(stride) == 2:
  132. stride_h = stride[0]
  133. stride_w = stride[1]
  134. elif isinstance(stride, tuple) and len(stride) == 4:
  135. stride_h = stride[2]
  136. stride_w = stride[3]
  137. else:
  138. raise ValueError(f"The \'stride\' should be an int number or "
  139. f"a tuple of two or four int numbers, but got {stride}")
  140. if isinstance(pad, int):
  141. pad_top = pad
  142. pad_bottom = pad
  143. pad_left = pad
  144. pad_right = pad
  145. elif isinstance(pad, tuple) and len(pad) == 2:
  146. pad_top = pad[0]
  147. pad_bottom = pad[0]
  148. pad_left = pad[1]
  149. pad_right = pad[1]
  150. elif isinstance(pad, tuple) and len(pad) == 4:
  151. pad_top, pad_bottom, pad_left, pad_right = pad
  152. else:
  153. raise ValueError(f"The \'pad\' should be an int number or "
  154. f"a tuple of two or four int numbers, but got {pad}")
  155. batch_num, channel, height, width = input_shape
  156. out_h = (height + pad_top + pad_bottom - filter_h) // stride_h + 1
  157. out_w = (width + pad_left + pad_right - filter_w) // stride_w + 1
  158. col = col.reshape(batch_num, out_h, out_w, channel, filter_h, filter_w) \
  159. .transpose(0, 3, 4, 5, 1, 2)
  160. img = np.zeros((batch_num,
  161. channel,
  162. height + pad_top + pad_bottom + stride_h - 1,
  163. width + pad_left + pad_right + stride_w - 1)) \
  164. .astype(col.dtype)
  165. for y in range(filter_h):
  166. y_max = y + stride_h * out_h
  167. for x in range(filter_w):
  168. x_max = x + stride_h * out_w
  169. img[:, :, y:y_max:stride_h, x:x_max:stride_h] += col[:, :, y, x, :, :]
  170. return img[:, :, pad_top:height + pad_bottom, pad_left:width + pad_right]
  171. def convolve(x, w, b=None, pad_mode="valid"):
  172. """
  173. Gets the discrete, linear convolution of two one-dimensional sequences.
  174. Args:
  175. x (numpy.ndarray): One-dimensional input array.
  176. w (numpy.ndarray): One-dimensional input array.
  177. b (numpy.ndarray): One-dimensional input array. Default: None.
  178. pad_mode (str): Padding mode which can be: "full" means returns the
  179. convolution at each point of overlap, with an output shape
  180. of (N+M-1,); "same" means returns output of length max(M, N);
  181. Amd "valid" means returns output of length max(M, N) - min(M, N)
  182. + 1. Default: "valid".
  183. Returns:
  184. numpy.ndarray, discrete, linear convolution of x and w, then plus b.
  185. """
  186. if pad_mode not in {"same", "valid"}:
  187. pad_mode = "full"
  188. y = np.convolve(x, w, pad_mode)
  189. if b:
  190. y += b
  191. return y
  192. def conv2d(x, weight, bias=None, stride=1, pad=0,
  193. dilation=1, groups=1, padding_mode='zeros'):
  194. """Convolution 2D."""
  195. # pylint: disable=unused-argument
  196. validator.check_value_type('stride', stride, (int, tuple), None)
  197. if isinstance(stride, int):
  198. stride = (stride, stride)
  199. elif len(stride) == 4:
  200. stride = (stride[2], stride[3])
  201. if len(stride) != 2 or (not isinstance(stride[0], int)) or \
  202. (not isinstance(stride[1], int)) or \
  203. stride[0] < 1 or stride[1] < 1:
  204. raise ValueError(f"The \'stride\' of \'conv2d\' should be an positive int number or "
  205. f"a tuple of two positive int numbers, but got {stride}")
  206. stride_h = stride[0]
  207. stride_w = stride[1]
  208. validator.check_value_type('dilation', dilation, (int, tuple), None)
  209. if isinstance(dilation, int):
  210. dilation = (dilation, dilation)
  211. elif len(dilation) == 4:
  212. dilation = (dilation[2], dilation[3])
  213. if len(dilation) != 2 or (not isinstance(dilation[0], int)) or \
  214. (not isinstance(dilation[1], int)) or \
  215. dilation[0] < 1 or dilation[1] < 1:
  216. raise ValueError(f"The \'dilation\' of \'conv2d\' should be an positive int number or "
  217. f"a tuple of two positive int numbers, but got {dilation}")
  218. dilation_h = dilation[0]
  219. dilation_w = dilation[1]
  220. if isinstance(pad, int):
  221. pad_top = pad
  222. pad_bottom = pad
  223. pad_left = pad
  224. pad_right = pad
  225. elif isinstance(pad, tuple) and len(pad) == 4:
  226. pad_top, pad_bottom, pad_left, pad_right = pad
  227. else:
  228. raise ValueError(f"The \'pad\' should be an int number or "
  229. f"a tuple of two or four int numbers, but got {pad}")
  230. batch_num, _, x_h, x_w = x.shape
  231. filter_num, _, filter_h, filter_w = weight.shape
  232. out_h = 1 + int((x_h + pad_top + pad_bottom - filter_h - (filter_h - 1) * (dilation_h - 1)) / stride_h)
  233. out_w = 1 + int((x_w + pad_left + pad_right - filter_w - (filter_w - 1) * (dilation_w - 1)) / stride_w)
  234. col = im2col(x, filter_h, filter_w, stride, pad, dilation)
  235. col_w = np.reshape(weight, (filter_num, -1)).T
  236. out = np.dot(col, col_w)
  237. out = out.reshape(batch_num, out_h, out_w, -1).transpose(0, 3, 1, 2)
  238. if bias is not None:
  239. out += bias
  240. return out
  241. def conv2d_backprop_filter(dout, x, w_size, stride=1, pad=0):
  242. """Backpropagation filter for conv2d."""
  243. filter_num, channel, filter_height, filter_width = w_size
  244. dout = dout.transpose(0, 2, 3, 1).reshape(-1, filter_num)
  245. col = im2col(x, filter_height, filter_width, stride, pad)
  246. dw = np.dot(col.T, dout)
  247. dw = dw.transpose(1, 0).reshape(filter_num, channel, filter_height, filter_width)
  248. return dw
  249. def conv2d_backprop_input(dout, x_size, weight, stride=1, pad=0):
  250. """Backpropagation input for conv2d."""
  251. filter_num, _, filter_h, filter_w = weight.shape
  252. dout = dout.transpose(0, 2, 3, 1).reshape(-1, filter_num)
  253. col_w = weight.reshape(filter_num, -1).T
  254. dcol = np.dot(dout, col_w.T)
  255. dx = col2im(dcol, x_size, filter_h, filter_w, stride, pad)
  256. return dx
  257. def flatten(x):
  258. """
  259. Flattens an array to one dimension.
  260. Args:
  261. x (numpy.ndarray): An array to be flattened.
  262. Returns:
  263. numpy.ndarray, a flattened array in one dimension.
  264. """
  265. return x.flatten()
  266. def flatten2(x):
  267. """
  268. Flattens an array to one dimension by reshape.
  269. Args:
  270. x (numpy.ndarray): An array to be flattened.
  271. Returns:
  272. numpy.ndarray, a flattened array in one dimension.
  273. """
  274. return x.reshape(1, -1)
  275. def flatten_batch(x):
  276. """
  277. Flattens a batch of arrays to one dimension.
  278. Args:
  279. x (numpy.ndarray): A batch of arrays to be flattened.
  280. Returns:
  281. numpy.ndarray, a flattened one dimension array.
  282. """
  283. return x.reshape(x.shape[0], -1)
  284. def flatten_grad(dout, x):
  285. """Grad of flatten."""
  286. dout = np.reshape(dout, x)
  287. return dout
  288. def im2col(img, filter_h, filter_w, stride=1, pad=0, dilation=1):
  289. """Rearranges an image to row vector."""
  290. if isinstance(stride, int):
  291. stride_h = stride
  292. stride_w = stride
  293. elif isinstance(stride, tuple) and len(stride) == 2:
  294. stride_h = stride[0]
  295. stride_w = stride[1]
  296. elif isinstance(stride, tuple) and len(stride) == 4:
  297. stride_h = stride[2]
  298. stride_w = stride[3]
  299. else:
  300. raise ValueError(f"The \'stride\' should be an int number or "
  301. f"a tuple of two or four int numbers, but got {stride}")
  302. if isinstance(dilation, int):
  303. dilation_h = dilation
  304. dilation_w = dilation
  305. elif isinstance(dilation, tuple) and len(dilation) == 2:
  306. dilation_h = dilation[0]
  307. dilation_w = dilation[1]
  308. elif isinstance(dilation, tuple) and len(dilation) == 4:
  309. dilation_h = dilation[2]
  310. dilation_w = dilation[3]
  311. else:
  312. raise ValueError(f"The \'dilation\' should be an int number or "
  313. f"a tuple of two or four int numbers, but got {dilation}")
  314. if isinstance(pad, int):
  315. pad_top = pad
  316. pad_bottom = pad
  317. pad_left = pad
  318. pad_right = pad
  319. elif isinstance(pad, tuple) and len(pad) == 4:
  320. pad_top, pad_bottom, pad_left, pad_right = pad
  321. else:
  322. raise ValueError(f"The \'pad\' should be an int number or "
  323. f"a tuple of two or four int numbers, but got {pad}")
  324. batch_num, channel, height, width = img.shape
  325. out_h = (height + pad_top + pad_bottom - filter_h - (filter_h - 1) * (dilation_h - 1)) // stride_h + 1
  326. out_w = (width + pad_left + pad_right - filter_w - (filter_w - 1) * (dilation_w - 1)) // stride_w + 1
  327. img = np.pad(img, [(0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)], 'constant')
  328. col = np.zeros((batch_num, channel, filter_h, filter_w, out_h, out_w)).astype(img.dtype)
  329. for y in range(filter_h):
  330. y_max = y + stride_h * out_h
  331. for x in range(filter_w):
  332. x_max = x + stride_h * out_w
  333. col[:, :, y, x, :, :] = img[:, :, y:y_max:stride_h, x:x_max:stride_h]
  334. col = col.transpose(0, 4, 5, 1, 2, 3).reshape(batch_num * out_h * out_w, -1)
  335. return col
  336. def matmul(x, w, b=None):
  337. """
  338. Dot product of array x and w, then plus array b if b is not None.
  339. Args:
  340. x (numpy.ndarray): Represents the input array.
  341. w (numpy.ndarray): Represents weights array.
  342. b (numpy.ndarray): Represents bias array which has the same shape as x. Default: None.
  343. Returns:
  344. numpy.ndarray, the result of (x*w + b).
  345. """
  346. y = np.dot(x, w)
  347. if b:
  348. y += b
  349. return y
  350. def max_pooling(x, pool_h, pool_w, stride):
  351. """Max pooling."""
  352. validator.check_integer("stride", stride, 0, Rel.GT, None)
  353. num, channel, height, width = x.shape
  354. out_h = (height - pool_h) // stride + 1
  355. out_w = (width - pool_w) // stride + 1
  356. col = im2col(x, pool_h, pool_w, stride)
  357. col = col.reshape(-1, pool_h * pool_w)
  358. out = np.max(col, axis=1)
  359. out = out.reshape((num, out_h, out_w, channel)).transpose(0, 3, 1, 2)
  360. return out
  361. def max_pool_grad(x, dout, pool_h, pool_w, stride):
  362. """Grad of max pooling."""
  363. dout = dout.transpose(0, 2, 3, 1)
  364. pool_size = pool_h * pool_w
  365. dmax = np.zeros((dout.size, pool_size), dout.dtype)
  366. col = im2col(x, pool_h, pool_w, stride)
  367. col = col.reshape(-1, pool_h * pool_w)
  368. arg_max = np.argmax(col, axis=1)
  369. dmax[np.arange(arg_max.size), arg_max.flatten()] = dout.flatten()
  370. dmax = dmax.reshape(dout.shape + (pool_size,))
  371. dcol = dmax.reshape(dmax.shape[0] * dmax.shape[1] * dmax.shape[2], -1)
  372. dx = col2im(dcol, x.shape, pool_h, pool_w, stride)
  373. return dx
  374. def max_pool_grad_with_argmax(x, dout, arg_max, pool_h, pool_w, stride):
  375. """Grad of max pooling with argmax."""
  376. dout = dout.transpose(0, 2, 3, 1)
  377. pool_size = pool_h * pool_w
  378. dmax = np.zeros((dout.size, pool_size), dout.dtype)
  379. dmax[np.arange(arg_max.size), arg_max.flatten()] = dout.flatten()
  380. dmax = dmax.reshape(dout.shape + (pool_size,))
  381. dcol = dmax.reshape(dmax.shape[0] * dmax.shape[1] * dmax.shape[2], -1)
  382. dx = col2im(dcol, x.shape, pool_h, pool_w, stride)
  383. return dx
  384. def max_pool_with_argmax(x, pool_h, pool_w, stride):
  385. """Max pooling with argmax."""
  386. validator.check_integer("stride", stride, 0, Rel.GT, None)
  387. num, channel, height, width = x.shape
  388. out_h = (height - pool_h) // stride + 1
  389. out_w = (width - pool_w) // stride + 1
  390. col = im2col(x, pool_h, pool_w, stride)
  391. col = col.reshape(-1, pool_h * pool_w)
  392. out = np.max(col, axis=1)
  393. out_argmax = np.argmax(col, axis=1)
  394. out = out.reshape((num, out_h, out_w, channel)).transpose(0, 3, 1, 2)
  395. out_argmax = out_argmax.reshape((num, out_h, out_w, channel)).transpose(0, 3, 1, 2)
  396. return out, out_argmax
  397. def relu(x):
  398. """
  399. Rectified linear unit.
  400. Args:
  401. x (numpy.ndarray): The input array.
  402. Returns:
  403. numpy.ndarray, the array applied relu.
  404. """
  405. return x * (x > 0)
  406. def relu_grad(y):
  407. """
  408. Grad of relu.
  409. Args:
  410. y (numpy.ndarray): The input array.
  411. Returns:
  412. numpy.ndarray, the array applied grad of relu.
  413. """
  414. y[y <= 0] = 0
  415. y[y > 0] = 1
  416. return y
  417. def sigmoid(x):
  418. """
  419. Sigmoid activation function.
  420. Args:
  421. x (numpy.ndarray): The input array.
  422. Returns:
  423. numpy.ndarray, the array applied sigmoid.
  424. """
  425. return 1 / (1 + np.exp(x * -1))
  426. def tanh(x):
  427. """
  428. Computes hyperbolic tangent element-wise.
  429. Args:
  430. x (numpy.ndarray): The input array.
  431. Returns:
  432. numpy.ndarray, the array applied tanh.
  433. """
  434. a = np.exp(x) - np.exp(x * -1)
  435. b = np.exp(x) + np.exp(x * -1)
  436. return a / b
  437. def softmax(x, axis=None):
  438. """
  439. Softmax function which is `softmax(x) = np.exp(x)/sum(np.exp(x))`.
  440. Args:
  441. x (numpy.ndarray): Input array.
  442. axis (Union[int, tuple[int]]): Axis to compute values along. Default: None.
  443. Returns:
  444. numpy.ndarray, has the same shape as x.
  445. """
  446. from scipy.special import softmax as scipy_softmax
  447. return scipy_softmax(x, axis)
  448. def softmax_cross_entropy_with_logits(logits, labels):
  449. sample_num = labels.shape[0]
  450. prob = softmax(logits)
  451. log_likelihood = -np.log(prob[range(sample_num)]) * labels
  452. loss = np.sum(log_likelihood)
  453. dx = prob.copy()
  454. dx[range(sample_num)] -= labels
  455. return loss, dx
  456. def shape(x):
  457. """
  458. Gets the array's dimensions.
  459. Args:
  460. x (numpy.ndarray): Input array.
  461. Returns:
  462. tuple, the shape/dimensions of the input array.
  463. """
  464. return np.array(np.shape(x))
  465. def expand_dims(x, axis):
  466. """
  467. Expands the shape of an array.
  468. Args:
  469. x (numpy.ndarray): Input array.
  470. axis (int): Position in the expanded axes where the new axis is placed.
  471. Returns:
  472. numpy.ndarray, view of input array with the number of dimensions increased by one.
  473. """
  474. return np.expand_dims(x, axis)
  475. def squeeze(x, axis):
  476. """
  477. Removes single-dimensional entries from the shape of an array.
  478. Args:
  479. x (numpy.ndarray): Input array.
  480. axis (Union[int, tuple[int]]): Selected subset of the single-dimensional entries in the shape.
  481. Returns:
  482. numpy.ndarray, the input numpy.ndarray, but with all or a subset of the dimensions of length
  483. 1 removed.
  484. """
  485. return np.squeeze(x, tuple(axis))
  486. def reshape(x, shp):
  487. """
  488. Applies a new shape to an array without changing its data.
  489. Args:
  490. x (numpy.ndarray): Input array.
  491. shp (tuple[int]): New shape to apply to x.
  492. Returns:
  493. numpy.ndarray, a new view object or a copy of input array.
  494. """
  495. return np.reshape(x, tuple(shp))
  496. def rank(x):
  497. """
  498. Gets number of array dimensions.
  499. Args:
  500. x (numpy.ndarray): Input array.
  501. Returns:
  502. int, number of input array dimensions.
  503. """
  504. return np.array(np.ndim(x))
  505. def logsoftmax(x):
  506. """
  507. Log softmax function.
  508. Args:
  509. x (numpy.ndarray): Input array.
  510. Returns:
  511. numpy.ndarray, the result of applying log softmax on the input array.
  512. """
  513. return np.array(np.log(softmax(x)))
  514. def transpose(x, axes=None):
  515. """
  516. Transposes an input array according to axes.
  517. Args:
  518. x (numpy.ndarray): Input array.
  519. axes (list): The axes to be transposed. Default: None.
  520. Returns:
  521. numpy.ndarray, transposed array.
  522. """
  523. return np.transpose(x, axes)
  524. def invert_permutation(x):
  525. """
  526. Gets the inverse permutation of an array.
  527. Args:
  528. x (numpy.ndarray): Input array.
  529. Returns:
  530. tuple, the inverse permutation of the input array.
  531. """
  532. x = np.array(x)
  533. y = np.argsort(x)
  534. return tuple(y)
  535. def select(cond, x, y):
  536. """
  537. Gets elements from x or y depending on cond.
  538. Args:
  539. cond (bool): Where True, yield x, otherwise yield y.
  540. x (numpy.ndarray): Values from which to choose.
  541. y (numpy.ndarray): Values from which to choose.
  542. Returns:
  543. numpy.ndarray, elements from x where condition is True, and elements from y elsewhere.
  544. """
  545. return np.where(cond, x, y)
  546. def sum_by_axis(x, axis):
  547. """
  548. Sum of array elements over a given axis.
  549. Args:
  550. x (numpy.ndarray): Input array.
  551. axis (Union[int, tuple[int]]): Axis or axes along which a sum is performed.
  552. Returns:
  553. numpy.ndarray, has the same shape as input array with the specified axis removed.
  554. """
  555. return np.sum(x, axis)
  556. def equal(x, y):
  557. """
  558. Gets (x == y) element-wise.
  559. Args:
  560. x (numpy.ndarray): Input array.
  561. y (numpy.ndarray): Input array.
  562. Returns:
  563. numpy.ndarray, element-wise comparison of x and y.
  564. """
  565. return np.equal(x, y)
  566. def not_equal(x, y):
  567. """
  568. Gets (x != y) element-wise.
  569. Args:
  570. x (numpy.ndarray): Input array.
  571. y (numpy.ndarray): Input array.
  572. Returns:
  573. numpy.ndarray, element-wise comparison of x and y.
  574. """
  575. return np.not_equal(x, y)
  576. def greater(x, y):
  577. """
  578. Get the truth value of (x > y) element-wise.
  579. Args:
  580. x (numpy.ndarray): Input array.
  581. y (numpy.ndarray): Input array.
  582. Returns:
  583. numpy.ndarray, element-wise comparison of x and y.
  584. """
  585. return np.greater(x, y)
  586. def less(x, y):
  587. """
  588. Get the truth value of (x < y) element-wise.
  589. Args:
  590. x (numpy.ndarray): Input array.
  591. y (numpy.ndarray): Input array.
  592. Returns:
  593. Array, element-wise comparison of x and y.
  594. """
  595. return np.less(x, y)
  596. def logical_not(x):
  597. """
  598. Gets the truth value of NOT x element-wise.
  599. Args:
  600. x (numpy.ndarray): Input array.
  601. Returns:
  602. bool, have the same shape as x of the NOT operation on elements of x.
  603. """
  604. return np.logical_not(x)
  605. def sqrt(x):
  606. """
  607. Gets the non-negative square-root of an numpy.ndarray, element-wise.
  608. Args:
  609. x (numpy.ndarray): Input array.
  610. Returns:
  611. numpy.ndarray, has the same shape as x, containing the positive square-root of each
  612. element in x.
  613. """
  614. return np.sqrt(x)
  615. def power(x, y):
  616. """
  617. First array elements raised to powers from second numpy.ndarray, element-wise.
  618. Args:
  619. x (numpy.ndarray): The bases array.
  620. y (numpy.ndarray): The exponents array.
  621. Returns:
  622. numpy.ndarray, the bases in x raised to the exponents in y.
  623. """
  624. return np.power(x, y)
  625. def exp(x):
  626. """
  627. Gets the exponential of all elements in the input array.
  628. Args:
  629. x (numpy.ndarray): Input array.
  630. Returns:
  631. numpy.ndarray, element-wise exponential of x.
  632. """
  633. return np.exp(x)
  634. def maximum(x, y):
  635. """
  636. Gets the max of x and y element-wise.
  637. If x > y, return x. Otherwise, return y.
  638. Args:
  639. x (numpy.ndarray): First input array.
  640. y (numpy.ndarray): Second input array ave the same type as x.
  641. Returns:
  642. numpy.ndarray, has the same type as x.
  643. """
  644. return np.maximum(x, y)
  645. def minimum(x, y):
  646. """
  647. Gets the min of x and y element-wise.
  648. If x < y, return x. Otherwise, return y.
  649. Args:
  650. x (numpy.ndarray): First input array.
  651. y (numpy.ndarray): Second input array have the same type as x.
  652. Returns:
  653. numpy.ndarray, has the same type as x.
  654. """
  655. return np.minimum(x, y)
  656. def all_(x, axis=(), keep_dims=False):
  657. """
  658. Check all array elements along a given axis evaluate to True.
  659. Args:
  660. x (numpy.ndarray): An array to be reduced.
  661. axis (Union[None, int, tuple(int)): Dimensions of reduction.
  662. keep_dims (bool): Whether to keep the reduced dimensions.
  663. Returns:
  664. numpy.ndarray, has the same type as x.
  665. """
  666. axis = None if axis == () else axis
  667. return np.all(x, axis, keepdims=keep_dims)
  668. def any_(x, axis=(), keep_dims=False):
  669. """
  670. Check any array element along a given axis evaluate to True.
  671. Args:
  672. x (numpy.ndarray): An array to be reduced.
  673. axis (Union[None, int, tuple(int)): Dimensions of reduction.
  674. keep_dims (bool): Whether to keep the reduced dimensions.
  675. Returns:
  676. numpy.ndarray, has the same type as x.
  677. """
  678. axis = None if axis == () else axis
  679. return np.any(x, axis, keepdims=keep_dims)