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 21 kB

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