r"""Returns sorted tensor and the indices would sort the input tensor. Args: inp: input tensor. The result would be sorted along the given dimension. descending: sort in descending order, where the largest comes first. Default: False dim: which dimension to sort along. D
(inp: Tensor, descending: bool = False, dim: int = -1)
| 611 | |
| 612 | |
| 613 | def sort(inp: Tensor, descending: bool = False, dim: int = -1) -> Tuple[Tensor, Tensor]: |
| 614 | r"""Returns sorted tensor and the indices would sort the input tensor. |
| 615 | |
| 616 | Args: |
| 617 | inp: input tensor. The result would be sorted along the given dimension. |
| 618 | descending: sort in descending order, where the largest comes first. Default: False |
| 619 | dim: which dimension to sort along. Default: -1 (last dimension) |
| 620 | |
| 621 | Returns: |
| 622 | tuple of two tensors `(sorted_tensor, indices_of_int32)`. |
| 623 | |
| 624 | Examples: |
| 625 | >>> import numpy as np |
| 626 | >>> x = Tensor(np.array([1,2], dtype=np.float32)) |
| 627 | >>> out, indices = F.sort(x) |
| 628 | >>> out.numpy() |
| 629 | array([1., 2.], dtype=float32) |
| 630 | """ |
| 631 | if descending: |
| 632 | order = "descending" |
| 633 | else: |
| 634 | order = "ascending" |
| 635 | |
| 636 | op = builtin.Argsort(order=order) |
| 637 | |
| 638 | transposed = swapaxes(inp, dim, -1) |
| 639 | transposed_shape = transposed.shape |
| 640 | nrows = transposed_shape[-1] |
| 641 | ncols = 1 |
| 642 | for i in range(len(transposed_shape) - 1): |
| 643 | ncols *= transposed_shape[i] |
| 644 | reshaped = transposed.reshape(ncols, nrows) |
| 645 | tns, ind = apply(op, reshaped) |
| 646 | |
| 647 | def restore(tensor): |
| 648 | unreshaped = tensor.reshape(transposed_shape) |
| 649 | untransposed = swapaxes(unreshaped, dim, -1) |
| 650 | return untransposed |
| 651 | |
| 652 | return restore(tns), restore(ind) |
| 653 | |
| 654 | |
| 655 | def topk( |