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.

basic.py 25 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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. """basic"""
  16. import numpy as np
  17. import mindspore.common.dtype as mstype
  18. from mindspore.common.tensor import Tensor
  19. from mindspore.common.initializer import initializer
  20. from mindspore._checkparam import check_int_positive, check_bool
  21. from mindspore.ops import operations as P
  22. from mindspore.ops import functional as F
  23. from mindspore.ops.functional import identity
  24. from mindspore.ops.operations import _inner_ops as inner
  25. from mindspore.ops.primitive import constexpr
  26. from mindspore.common.parameter import Parameter
  27. from mindspore._extends import cell_attr_register
  28. from mindspore.common.api import ms_function
  29. from mindspore import context
  30. from mindspore.ops import _selected_ops
  31. from ..cell import Cell
  32. from .activation import get_activation
  33. from ..._checkparam import Validator as validator
  34. from ..._checkparam import Rel
  35. __all__ = ['Dropout', 'Flatten', 'Dense', 'ClipByNorm', 'Norm', 'OneHot', 'Pad', 'Unfold',
  36. 'MatrixDiag', 'MatrixDiagPart', 'MatrixSetDiag']
  37. class Dropout(Cell):
  38. r"""
  39. Dropout layer for the input.
  40. Randomly set some elements of the input tensor to zero with probability :math:`1 - keep\_prob` during training
  41. using samples from a Bernoulli distribution.
  42. Note:
  43. Each channel will be zeroed out independently on every construct call.
  44. The outputs are scaled by a factor of :math:`\frac{1}{keep\_prob}` during training so
  45. that the output layer remains at a similar scale. During inference, this
  46. layer returns the same tensor as the input.
  47. This technique is proposed in paper `Dropout: A Simple Way to Prevent Neural Networks from Overfitting
  48. <http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf>`_ and proved to be effective to reduce
  49. over-fitting and prevents neurons from co-adaptation. See more details in `Improving neural networks by
  50. preventing co-adaptation of feature detectors
  51. <https://arxiv.org/pdf/1207.0580.pdf>`_.
  52. Args:
  53. keep_prob (float): The keep rate, greater than 0 and less equal than 1. E.g. rate=0.9,
  54. dropping out 10% of input units. Default: 0.5.
  55. seed0 (int): The first random seed. Default: 0.
  56. seed1 (int): The second random seed. Default: 0.
  57. dtype (:class:`mindspore.dtype`): Data type of input. Default: mindspore.float32.
  58. Raises:
  59. ValueError: If `keep_prob` is not in range (0, 1).
  60. Inputs:
  61. - **input** (Tensor) - An N-D Tensor.
  62. Outputs:
  63. Tensor, output tensor with the same shape as the input.
  64. Examples:
  65. >>> x = Tensor(np.ones([20, 16, 50]), mindspore.float32)
  66. >>> net = nn.Dropout(keep_prob=0.8)
  67. >>> net(x)
  68. """
  69. def __init__(self, keep_prob=0.5, seed0=0, seed1=0, dtype=mstype.float32):
  70. super(Dropout, self).__init__()
  71. if keep_prob <= 0 or keep_prob > 1:
  72. raise ValueError("dropout probability should be a number in range (0, 1], but got {}".format(keep_prob))
  73. validator.check_subclass("dtype", dtype, mstype.number_type, self.cls_name)
  74. self.keep_prob = keep_prob
  75. self.seed0 = seed0
  76. self.seed1 = seed1
  77. self.dtype = dtype
  78. self.get_shape = P.Shape()
  79. self.dropout_gen_mask = P.DropoutGenMask(Seed0=seed0, Seed1=seed1)
  80. self.dropout_do_mask = P.DropoutDoMask()
  81. self.cast = P.Cast()
  82. self.is_gpu = context.get_context('device_target') in ["GPU"]
  83. self.dropout = P.Dropout(keep_prob)
  84. def construct(self, x):
  85. if not self.training:
  86. return x
  87. if self.is_gpu:
  88. out, _ = self.dropout(x)
  89. return out
  90. if self.keep_prob == 1:
  91. return x
  92. shape = self.get_shape(x)
  93. dtype = P.DType()(x)
  94. keep_prob = self.cast(self.keep_prob, dtype)
  95. output = self.dropout_gen_mask(shape, keep_prob)
  96. return self.dropout_do_mask(x, output, keep_prob)
  97. def extend_repr(self):
  98. str_info = 'keep_prob={}, Seed0={}, Seed1={}, dtype={}' \
  99. .format(self.keep_prob, self.seed0, self.seed1, self.dtype)
  100. return str_info
  101. class Flatten(Cell):
  102. r"""
  103. Flatten layer for the input.
  104. Flattens a tensor without changing dimension of batch size on the 0-th axis.
  105. Inputs:
  106. - **input** (Tensor) - Tensor of shape :math:`(N, \ldots)` to be flattened.
  107. Outputs:
  108. Tensor, the shape of the output tensor is :math:`(N, X)`, where :math:`X` is
  109. the product of the remaining dimensions.
  110. Examples:
  111. >>> net = nn.Flatten()
  112. >>> input = Tensor(np.array([[[1.2, 1.2], [2.1, 2.1]], [[2.2, 2.2], [3.2, 3.2]]]), mindspore.float32)
  113. >>> input.shape
  114. (2, 2, 2)
  115. >>> net(input)
  116. [[1.2 1.2 2.1 2.1]
  117. [2.2 2.2 3.2 3.2]]
  118. """
  119. def __init__(self):
  120. super(Flatten, self).__init__()
  121. def construct(self, x):
  122. return F.reshape(x, (F.shape(x)[0], -1))
  123. class Dense(Cell):
  124. r"""
  125. The fully connected layer.
  126. Applies dense-connected layer for the input. This layer implements the operation as:
  127. .. math::
  128. \text{outputs} = \text{activation}(\text{inputs} * \text{kernel} + \text{bias}),
  129. where :math:`\text{activation}` is the activation function passed as the activation
  130. argument (if passed in), :math:`\text{activation}` is a weight matrix with the same
  131. data type as the inputs created by the layer, and :math:`\text{bias}` is a bias vector
  132. with the same data type as the inputs created by the layer (only if has_bias is True).
  133. Args:
  134. in_channels (int): The number of channels in the input space.
  135. out_channels (int): The number of channels in the output space.
  136. weight_init (Union[Tensor, str, Initializer, numbers.Number]): The trainable weight_init parameter. The dtype
  137. is same as input x. The values of str refer to the function `initializer`. Default: 'normal'.
  138. bias_init (Union[Tensor, str, Initializer, numbers.Number]): The trainable bias_init parameter. The dtype is
  139. same as input x. The values of str refer to the function `initializer`. Default: 'zeros'.
  140. has_bias (bool): Specifies whether the layer uses a bias vector. Default: True.
  141. activation (str): activate function applied to the output of the fully connected layer, eg. 'ReLU'.
  142. Default: None.
  143. Raises:
  144. ValueError: If weight_init or bias_init shape is incorrect.
  145. Inputs:
  146. - **input** (Tensor) - Tensor of shape :math:`(N, in\_channels)`.
  147. Outputs:
  148. Tensor of shape :math:`(N, out\_channels)`.
  149. Examples:
  150. >>> net = nn.Dense(3, 4)
  151. >>> input = Tensor(np.random.randint(0, 255, [2, 3]), mindspore.float32)
  152. >>> net(input)
  153. [[ 2.5246444 2.2738023 0.5711005 -3.9399147 ]
  154. [ 1.0739875 4.0155234 0.94188046 -5.459526 ]]
  155. """
  156. @cell_attr_register(attrs=['has_bias', 'activation'])
  157. def __init__(self,
  158. in_channels,
  159. out_channels,
  160. weight_init='normal',
  161. bias_init='zeros',
  162. has_bias=True,
  163. activation=None):
  164. super(Dense, self).__init__()
  165. self.in_channels = check_int_positive(in_channels)
  166. self.out_channels = check_int_positive(out_channels)
  167. self.has_bias = check_bool(has_bias)
  168. if isinstance(weight_init, Tensor):
  169. if weight_init.dim() != 2 or weight_init.shape[0] != out_channels or \
  170. weight_init.shape[1] != in_channels:
  171. raise ValueError("weight_init shape error")
  172. self.weight = Parameter(initializer(weight_init, [out_channels, in_channels]), name="weight")
  173. if self.has_bias:
  174. if isinstance(bias_init, Tensor):
  175. if bias_init.dim() != 1 or bias_init.shape[0] != out_channels:
  176. raise ValueError("bias_init shape error")
  177. self.bias = Parameter(initializer(bias_init, [out_channels]), name="bias")
  178. self.matmul = P.MatMul(transpose_b=True)
  179. self.bias_add = _selected_ops.BiasAdd()
  180. self.activation = get_activation(activation)
  181. self.activation_flag = self.activation is not None
  182. def construct(self, x):
  183. output = self.matmul(x, self.weight)
  184. if self.has_bias:
  185. output = self.bias_add(output, self.bias)
  186. if self.activation_flag:
  187. return self.activation(output)
  188. return output
  189. def extend_repr(self):
  190. str_info = 'in_channels={}, out_channels={}, weight={}, has_bias={}' \
  191. .format(self.in_channels, self.out_channels, self.weight, self.has_bias)
  192. if self.has_bias:
  193. str_info = str_info + ', bias={}'.format(self.bias)
  194. if self.activation_flag:
  195. str_info = str_info + ', activation={}'.format(self.activation)
  196. return str_info
  197. @constexpr
  198. def _is_equal_one(x):
  199. if x is None:
  200. return False
  201. return bool(x.asnumpy().mean() == 1.0)
  202. @constexpr
  203. def _dtype_check(x_dtype):
  204. if x_dtype not in [mstype.float32, mstype.float16]:
  205. raise TypeError("The input type must be float32 or float16.")
  206. class ClipByNorm(Cell):
  207. r"""
  208. Clips tensor values to a maximum :math:`L_2`-norm.
  209. The output of this layer remains the same if the :math:`L_2`-norm of the input tensor
  210. is not greater than the argument clip_norm. Otherwise the tensor will be normalized as:
  211. .. math::
  212. \text{output}(X) = \frac{\text{clip_norm} * X}{L_2(X)},
  213. where :math:`L_2(X)` is the :math:`L_2`-norm of :math:`X`.
  214. Inputs:
  215. - **input** (Tensor) - Tensor of shape N-D. The type should be float32 or float16.
  216. - **clip_norm** (Tensor) - A scalar Tensor of shape :math:`()` or :math:`(1)`.
  217. Outputs:
  218. Tensor, clipped tensor with the same shape as the input, whose type is float32.
  219. Examples:
  220. >>> net = nn.ClipByNorm()
  221. >>> input = Tensor(np.random.randint(0, 10, [4, 16]), mindspore.float32)
  222. >>> clip_norm = Tensor(np.array([100]).astype(np.float32))
  223. >>> net(input, clip_norm)
  224. """
  225. def __init__(self):
  226. super(ClipByNorm, self).__init__()
  227. self.reduce_sum = P.ReduceSum(keep_dims=True)
  228. self.select_ = P.Select()
  229. self.greater_ = P.Greater()
  230. self.cast = P.Cast()
  231. self.sqrt = P.Sqrt()
  232. self.max_op = P.Maximum()
  233. self.shape = P.Shape()
  234. self.reshape = P.Reshape()
  235. self.fill = P.Fill()
  236. self.expand_dims = P.ExpandDims()
  237. self.dtype = P.DType()
  238. @ms_function
  239. def construct(self, x, clip_norm):
  240. """add ms_function decorator for pynative mode"""
  241. mul_x = F.square(x)
  242. l2sum = self.cast(self.reduce_sum(mul_x), mstype.float32)
  243. cond = self.greater_(l2sum, 0)
  244. ones_ = self.fill(self.dtype(cond), self.shape(cond), 1.0)
  245. l2sum_safe = self.select_(cond, l2sum, self.cast(ones_, self.dtype(l2sum)))
  246. l2norm = self.select_(cond, self.sqrt(l2sum_safe), l2sum)
  247. _dtype_check(self.dtype(x))
  248. if _is_equal_one(clip_norm):
  249. intermediate = x
  250. else:
  251. intermediate = x * clip_norm
  252. max_norm = self.max_op(l2norm, clip_norm)
  253. values_clip = self.cast(intermediate, mstype.float32) / self.expand_dims(max_norm, -1)
  254. values_clip = self.reshape(values_clip, self.shape(x))
  255. values_clip = identity(values_clip)
  256. return values_clip
  257. class Norm(Cell):
  258. """
  259. Computes the norm of vectors, currently including Euclidean norm, i.e., :math:`L_2`-norm.
  260. Args:
  261. axis (tuple): The axis over which to compute vector norms. Default: ().
  262. keep_dims (bool): If True, the axis indicated in `axis` are kept with size 1. Otherwise,
  263. the dimensions in `axis` are removed from the output shape. Default: False.
  264. Inputs:
  265. - **input** (Tensor) - Tensor which is not empty.
  266. Outputs:
  267. Tensor, output tensor with dimensions in 'axis' reduced to 1 will be returned if 'keep_dims' is True;
  268. otherwise a Tensor with dimensions in 'axis' removed is returned.
  269. Examples:
  270. >>> net = nn.Norm(axis=0)
  271. >>> input = Tensor(np.random.randint(0, 10, [4, 16]), mindspore.float32)
  272. >>> net(input)
  273. """
  274. def __init__(self, axis=(), keep_dims=False):
  275. super(Norm, self).__init__()
  276. self.axis = axis
  277. self.keep_dims = keep_dims
  278. self.reduce_sum = P.ReduceSum(True)
  279. self.sqrt = P.Sqrt()
  280. self.squeeze = P.Squeeze(self.axis)
  281. def construct(self, x):
  282. x = self.sqrt(self.reduce_sum(F.square(x), self.axis))
  283. if not self.keep_dims:
  284. x = self.squeeze(x)
  285. return x
  286. def extend_repr(self):
  287. str_info = 'axis={}, keep_dims={}'.format(self.axis, self.keep_dims)
  288. return str_info
  289. class OneHot(Cell):
  290. """
  291. Returns a one-hot tensor.
  292. The locations represented by indices in argument 'indices' take value on_value,
  293. while all other locations take value off_value.
  294. Note:
  295. If the input indices is rank :math:`N`, the output will have rank :math:`N+1`. The new
  296. axis is created at dimension `axis`.
  297. Args:
  298. axis (int): Features x depth if axis is -1, depth x features
  299. if axis is 0. Default: -1.
  300. depth (int): A scalar defining the depth of the one hot dimension. Default: 1.
  301. on_value (float): A scalar defining the value to fill in output[i][j]
  302. when indices[j] = i. Default: 1.0.
  303. off_value (float): A scalar defining the value to fill in output[i][j]
  304. when indices[j] != i. Default: 0.0.
  305. dtype (:class:`mindspore.dtype`): Data type of 'on_value' and 'off_value', not the
  306. data type of indices. Default: mindspore.float32.
  307. Inputs:
  308. - **indices** (Tensor) - A tensor of indices of data type mindspore.int32 and arbitrary shape.
  309. Outputs:
  310. Tensor, the one-hot tensor of data type 'dtype' with dimension at 'axis' expanded to 'depth' and filled with
  311. on_value and off_value.
  312. Examples:
  313. >>> net = nn.OneHot(depth=4, axis=1)
  314. >>> indices = Tensor([[1, 3], [0, 2]], dtype=mindspore.int32)
  315. >>> net(indices)
  316. [[[0. 0.]
  317. [1. 0.]
  318. [0. 0.]
  319. [0. 1.]]
  320. [[1. 0.]
  321. [0. 0.]
  322. [0. 1.]
  323. [0. 0.]]]
  324. """
  325. def __init__(self, axis=-1, depth=1, on_value=1.0, off_value=0.0, dtype=mstype.float32):
  326. super(OneHot, self).__init__()
  327. self.onehot = P.OneHot(axis)
  328. self.depth = depth
  329. self.dtype = dtype
  330. self.on_value = on_value
  331. self.off_value = off_value
  332. def construct(self, indices):
  333. return self.onehot(indices, self.depth, F.cast(self.on_value, self.dtype), F.cast(self.off_value, self.dtype))
  334. class Pad(Cell):
  335. """
  336. Pads the input tensor according to the paddings and mode.
  337. Args:
  338. paddings (tuple): The shape of parameter `paddings` is (N, 2). N is the rank of input data. All elements of
  339. paddings are int type. For `D` th dimension of input, paddings[D, 0] indicates how many sizes to be
  340. extended ahead of the `D` th dimension of the input tensor, and paddings[D, 1] indicates how many sizes to
  341. be extended behind of the `D` th dimension of the input tensor.
  342. mode (str): Specifies padding mode. The optional values are "CONSTANT", "REFLECT", "SYMMETRIC".
  343. Default: "CONSTANT".
  344. Inputs:
  345. - **input_x** (Tensor) - The input tensor.
  346. Outputs:
  347. Tensor, the tensor after padding.
  348. - If `mode` is "CONSTANT", it fills the edge with 0, regardless of the values of the `input_x`.
  349. If the `input_x` is [[1,2,3],[4,5,6],[7,8,9]] and `paddings` is [[1,1],[2,2]], then the
  350. Outputs is [[0,0,0,0,0,0,0],[0,0,1,2,3,0,0],[0,0,4,5,6,0,0],[0,0,7,8,9,0,0],[0,0,0,0,0,0,0]].
  351. - If `mode` is "REFLECT", it uses a way of symmetrical copying throught the axis of symmetry to fill in.
  352. If the `input_x` is [[1,2,3],[4,5,6],[7,8,9]] and `paddings` is [[1,1],[2,2]], then the
  353. Outputs is [[6,5,4,5,6,5,4],[3,2,1,2,3,2,1],[6,5,4,5,6,5,4],[9,8,7,8,9,8,7],[6,5,4,5,6,5,4]].
  354. - If `mode` is "SYMMETRIC", the filling method is similar to the "REFLECT". It is also copied
  355. according to the symmetry axis, except that it includes the symmetry axis. If the `input_x`
  356. is [[1,2,3],[4,5,6],[7,8,9]] and `paddings` is [[1,1],[2,2]], then the Outputs is
  357. [[2,1,1,2,3,3,2],[2,1,1,2,3,3,2],[5,4,4,5,6,6,5],[8,7,7,8,9,9,8],[8,7,7,8,9,9,8]].
  358. Examples:
  359. >>> from mindspore import Tensor
  360. >>> from mindspore.ops import operations as P
  361. >>> import mindspore.nn as nn
  362. >>> import numpy as np
  363. >>> class Net(nn.Cell):
  364. >>> def __init__(self):
  365. >>> super(Net, self).__init__()
  366. >>> self.pad = nn.Pad(paddings=((1,1),(2,2)), mode="CONSTANT")
  367. >>> def construct(self, x):
  368. >>> return self.pad(x)
  369. >>> x = np.random.random(size=(2, 3)).astype(np.float32)
  370. >>> pad = Net()
  371. >>> ms_output = pad(Tensor(x))
  372. """
  373. def __init__(self, paddings, mode="CONSTANT"):
  374. super(Pad, self).__init__()
  375. self.mode = mode
  376. self.paddings = paddings
  377. validator.check_string('mode', self.mode, ["CONSTANT", "REFLECT", "SYMMETRIC"], self.cls_name)
  378. if not isinstance(paddings, tuple):
  379. raise TypeError('Paddings must be tuple type.')
  380. for item in paddings:
  381. if len(item) != 2:
  382. raise ValueError('The shape of paddings must be (n, 2).')
  383. if mode == "CONSTANT":
  384. self.pad = P.Pad(self.paddings)
  385. else:
  386. self.paddings = Tensor(np.array(self.paddings))
  387. self.pad = P.MirrorPad(mode=mode)
  388. def construct(self, x):
  389. if self.mode == "CONSTANT":
  390. x = self.pad(x)
  391. else:
  392. x = self.pad(x, self.paddings)
  393. return x
  394. class Unfold(Cell):
  395. """
  396. Extract patches from images.
  397. The input tensor must be a 4-D tensor and the data format is NCHW.
  398. Args:
  399. ksizes (Union[tuple[int], list[int]]): The size of sliding window, should be a tuple or a list of integers,
  400. and the format is [1, ksize_row, ksize_col, 1].
  401. strides (Union[tuple[int], list[int]]): Distance between the centers of the two consecutive patches,
  402. should be a tuple or list of int, and the format is [1, stride_row, stride_col, 1].
  403. rates (Union[tuple[int], list[int]]): In each extracted patch, the gap between the corresponding dimension
  404. pixel positions, should be a tuple or a list of integers, and the format is [1, rate_row, rate_col, 1].
  405. padding (str): The type of padding algorithm, is a string whose value is "same" or "valid",
  406. not case sensitive. Default: "valid".
  407. - same: Means that the patch can take the part beyond the original image, and this part is filled with 0.
  408. - valid: Means that the taken patch area must be completely covered in the original image.
  409. Inputs:
  410. - **input_x** (Tensor) - A 4-D tensor whose shape is [in_batch, in_depth, in_row, in_col] and
  411. data type is number.
  412. Outputs:
  413. Tensor, a 4-D tensor whose data type is same as 'input_x',
  414. and the shape is [out_batch, out_depth, out_row, out_col], the out_batch is the same as the in_batch.
  415. Examples:
  416. >>> net = Unfold(ksizes=[1, 2, 2, 1], strides=[1, 1, 1, 1], rates=[1, 1, 1, 1])
  417. >>> image = Tensor(np.ones([1, 1, 3, 3]), dtype=mstype.float16)
  418. >>> net(image)
  419. Tensor ([[[[1, 1] [1, 1]] [[1, 1], [1, 1]] [[1, 1] [1, 1]], [[1, 1], [1, 1]]]],
  420. shape=(1, 4, 2, 2), dtype=mstype.float16)
  421. """
  422. def __init__(self, ksizes, strides, rates, padding="valid"):
  423. super(Unfold, self).__init__()
  424. self.extract_image_patches = inner.ExtractImagePatches(ksizes, strides, rates, padding)
  425. self.transpose = P.Transpose()
  426. self.format_NHWC = (0, 2, 3, 1)
  427. self.format_NCHW = (0, 3, 1, 2)
  428. def construct(self, input_x):
  429. x_transpose = self.transpose(input_x, self.format_NHWC)
  430. ret = self.extract_image_patches(x_transpose)
  431. ret_transpose = self.transpose(ret, self.format_NCHW)
  432. return ret_transpose
  433. @constexpr
  434. def _get_matrix_diag_assist(x_shape, x_dtype):
  435. validator.check_integer("x rank", len(x_shape), 1, Rel.GE, "_get_matrix_diag_assist")
  436. base_eye = np.eye(x_shape[-1], x_shape[-1]).reshape(-1)
  437. assist = np.tile(base_eye, x_shape[:-1]).reshape(x_shape + (x_shape[-1],))
  438. return Tensor(assist, x_dtype)
  439. @constexpr
  440. def _get_matrix_diag_part_assist(x_shape, x_dtype):
  441. validator.check_integer("x rank", len(x_shape), 2, Rel.GE, "_get_matrix_diag_part_assist")
  442. base_eye = np.eye(x_shape[-2], x_shape[-1]).reshape(-1)
  443. assist = np.tile(base_eye, x_shape[:-2]).reshape(x_shape)
  444. return Tensor(assist, x_dtype)
  445. class MatrixDiag(Cell):
  446. """
  447. Returns a batched diagonal tensor with a given batched diagonal values.
  448. Inputs:
  449. - **x** (Tensor) - The diagonal values. It can be one of the following data types:
  450. float32, float16, int32, int8, and uint8.
  451. Outputs:
  452. Tensor, has the same type as input `x`. The shape should be x.shape + (x.shape[-1], ).
  453. Examples:
  454. >>> x = Tensor(np.array([1, -1]), mstype.float32)
  455. >>> matrix_diag = nn.MatrixDiag()
  456. >>> result = matrix_diag(x)
  457. [[1. 0.]
  458. [0. -1.]]
  459. """
  460. def __init__(self):
  461. super(MatrixDiag, self).__init__()
  462. self.matrix_diag = inner.MatrixDiag()
  463. self.dtype = P.DType()
  464. def construct(self, input_x):
  465. x_shape = F.shape(input_x)
  466. x_dtype = self.dtype(input_x)
  467. assist = _get_matrix_diag_assist(x_shape, x_dtype)
  468. out_matrix_diag = self.matrix_diag(input_x, assist)
  469. return out_matrix_diag
  470. class MatrixDiagPart(Cell):
  471. r"""
  472. Returns the batched diagonal part of a batched tensor.
  473. Inputs:
  474. - **x** (Tensor) - The batched tensor. It can be one of the following data types:
  475. float32, float16, int32, int8, and uint8.
  476. Outputs:
  477. Tensor, has the same type as input `x`. The shape should be x.shape[:-2] + [min(x.shape[-2:])].
  478. Examples:
  479. >>> x = Tensor([[[-1, 0], [0, 1]], [[-1, 0], [0, 1]], [[-1, 0], [0, 1]]], mindspore.float32)
  480. >>> matrix_diag_part = nn.MatrixDiagPart()
  481. >>> result = matrix_diag_part(x)
  482. [[-1., 1.], [-1., 1.], [-1., 1.]]
  483. """
  484. def __init__(self):
  485. super(MatrixDiagPart, self).__init__()
  486. self.matrix_diag_part = inner.MatrixDiagPart()
  487. self.dtype = P.DType()
  488. def construct(self, input_x):
  489. x_shape = F.shape(input_x)
  490. x_dtype = self.dtype(input_x)
  491. assist = _get_matrix_diag_part_assist(x_shape, x_dtype)
  492. out_matrix_diag_part = self.matrix_diag_part(input_x, assist)
  493. return out_matrix_diag_part
  494. class MatrixSetDiag(Cell):
  495. r"""
  496. Modify the batched diagonal part of a batched tensor.
  497. Inputs:
  498. - **x** (Tensor) - The batched tensor. It can be one of the following data types:
  499. float32, float16, int32, int8, and uint8.
  500. - **diagonal** (Tensor) - The diagonal values.
  501. Outputs:
  502. Tensor, has the same type and shape as input `x`.
  503. Examples:
  504. >>> x = Tensor([[[-1, 0], [0, 1]], [[-1, 0], [0, 1]], [[-1, 0], [0, 1]]], mindspore.float32)
  505. >>> diagonal = Tensor([[-1., 2.], [-1., 1.], [-1., 1.]], mindspore.float32)
  506. >>> matrix_set_diag = nn.MatrixSetDiag()
  507. >>> result = matrix_set_diag(x, diagonal)
  508. [[[-1, 0], [0, 2]], [[-1, 0], [0, 1]], [[-1, 0], [0, 1]]]
  509. """
  510. def __init__(self):
  511. super(MatrixSetDiag, self).__init__()
  512. self.matrix_set_diag = inner.MatrixSetDiag()
  513. self.dtype = P.DType()
  514. def construct(self, input_x, diagonal):
  515. x_shape = F.shape(input_x)
  516. x_dtype = self.dtype(input_x)
  517. assist = _get_matrix_diag_part_assist(x_shape, x_dtype)
  518. out_matrix_set_diag = self.matrix_set_diag(input_x, diagonal, assist)
  519. return out_matrix_set_diag