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

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