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.

array_creations.py 92 kB

5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
optimize the comment and log description 修改: ops/operations/_inner_ops.py 修改: ops/operations/_quant_ops.py 修改: ops/operations/array_ops.py 修改: ops/operations/comm_ops.py 修改: ops/operations/math_ops.py 修改: ops/operations/quantum_ops.py 修改: ops/operations/rl_ops.py 修改: ops/operations/sponge_ops.py 修改: ops/operations/sponge_update_ops.py 修改: train/__init__.py 修改: common/tensor.py 修改: train/serialization.py 修改: ccsrc/pipeline/jit/parse/parse.h 修改: explainer/benchmark/_attribution/metric.py 修改: ops/composite/multitype_ops/_constexpr_utils.py 修改: ops/operations/comm_ops.py 修改: RELEASE.md 修改: mindspore/_extends/parse/standard_method.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/concat_offset_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/dynamic_shape_cpu_kernel.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/reshape_info.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/tile_info.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/transpose_info.cc 修改: mindspore/ccsrc/frontend/parallel/strategy.h 修改: mindspore/common/tensor.py 修改: mindspore/core/abstract/prim_arrays.cc 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/core/ops/conv2d.cc 修改: mindspore/core/ops/logical_and.h 修改: mindspore/core/ops/logical_not.h 修改: mindspore/core/ops/logical_or.h 修改: mindspore/core/ops/reduce_all.h 修改: mindspore/core/ops/reduce_any.h 修改: mindspore/lite/src/runtime/kernel/arm/fp32_grad/sgd.cc 修改: mindspore/nn/layer/quant.py 修改: mindspore/nn/optim/sgd.py 修改: mindspore/nn/sparse/sparse.py 修改: mindspore/numpy/array_creations.py 修改: mindspore/numpy/array_ops.py 修改: mindspore/numpy/logic_ops.py 修改: mindspore/numpy/math_ops.py 修改: mindspore/ops/operations/_inner_ops.py 修改: mindspore/ops/operations/array_ops.py 修改: mindspore/ops/operations/rl_ops.py 修改: mindspore/train/_utils.py 修改: tests/ut/python/model/test_lenet_core_after_exception.py 修改: mindspore/_extends/parse/standard_method.py 修改: mindspore/ops/operations/rl_ops.py 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/core/ops/conv2d.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ctcloss_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/fl/fused_pull_weight_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/fl/fused_push_weight_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/mkldnn/conv2d_grad_filter_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/mkldnn/conv2d_grad_input_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ps/sparse_apply_ftrl_ps_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ps/sparse_apply_lazy_adam_ps_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/rolling_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/scatter_arithmetic_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/split_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/update_cache_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/split_gpu_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/math/broadcast_gpu_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/nn/conv2d_grad_input_gpu_kernel.h 修改: mindspore/ccsrc/fl/server/server.cc 修改: mindspore/ccsrc/frontend/optimizer/ad/kpynative.cc 修改: mindspore/ccsrc/frontend/optimizer/irpass/incorporate_getitem.h 修改: mindspore/ccsrc/frontend/optimizer/irpass/inline.h 修改: mindspore/ccsrc/minddata/dataset/core/device_tensor.cc 修改: mindspore/ccsrc/minddata/dataset/core/tensor.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/mnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/qmnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/dataset_node.cc 修改: mindspore/ccsrc/minddata/dataset/engine/opt/pre/epoch_ctrl_pass.cc 修改: mindspore/ccsrc/minddata/dataset/kernels/image/lite_image_utils.cc 修改: mindspore/ccsrc/pipeline/jit/action.cc 修改: mindspore/ccsrc/pipeline/jit/static_analysis/evaluator.cc 修改: mindspore/ccsrc/runtime/device/ascend/executor/tiling/op_tiling_adapter.cc 修改: mindspore/compression/quant/quant_utils.py 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/dataset/engine/validators.py 修改: mindspore/lite/micro/coder/opcoders/nnacl/fp32/affine_fp32_coder.cc 修改: mindspore/lite/micro/coder/opcoders/nnacl/int8/affine_int8_coder.cc 修改: mindspore/lite/src/runtime/kernel/ascend310/src/custom_kernel.cc 修改: mindspore/lite/src/runtime/kernel/opencl/kernel/matmul.cc 修改: mindspore/lite/src/runtime/kernel/opencl/kernel/strassen.cc 修改: mindspore/lite/tools/common/graph_util.h 修改: mindspore/lite/tools/optimizer/fisson/fisson_util.cc 修改: mindspore/ops/composite/math_ops.py 修改: mindspore/ops/operations/_inner_ops.py 修改: mindspore/ops/operations/array_ops.py 修改: mindspore/ops/operations/math_ops.py 修改: mindspore/ops/operations/other_ops.py 修改: mindspore/boost/boost_cell_wrapper.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/update_cache_cpu_kernel.cc 修改: mindspore/ccsrc/common/trans.cc 修改: mindspore/ccsrc/frontend/parallel/cache_embedding/cache_embedding.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/gather_info.cc 修改: mindspore/lite/src/common/log_util.h 修改: mindspore/nn/wrap/loss_scale.py 修改: mindspore/parallel/nn/moe.py 修改: tests/mindspore_test_framework/mindspore_test.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/split_cpu_kernel.cc 修改: mindspore/lite/tools/common/graph_util.h 修改: mindspore/ccsrc/frontend/parallel/ops_info/gather_info.cc 修改: mindspore/core/ops/conv2d.cc 修改: tests/ut/python/model/test_lenet_core_after_exception.py
4 years ago
optimize the comment and log description 修改: ops/operations/_inner_ops.py 修改: ops/operations/_quant_ops.py 修改: ops/operations/array_ops.py 修改: ops/operations/comm_ops.py 修改: ops/operations/math_ops.py 修改: ops/operations/quantum_ops.py 修改: ops/operations/rl_ops.py 修改: ops/operations/sponge_ops.py 修改: ops/operations/sponge_update_ops.py 修改: train/__init__.py 修改: common/tensor.py 修改: train/serialization.py 修改: ccsrc/pipeline/jit/parse/parse.h 修改: explainer/benchmark/_attribution/metric.py 修改: ops/composite/multitype_ops/_constexpr_utils.py 修改: ops/operations/comm_ops.py 修改: RELEASE.md 修改: mindspore/_extends/parse/standard_method.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/concat_offset_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/dynamic_shape_cpu_kernel.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/reshape_info.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/tile_info.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/transpose_info.cc 修改: mindspore/ccsrc/frontend/parallel/strategy.h 修改: mindspore/common/tensor.py 修改: mindspore/core/abstract/prim_arrays.cc 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/core/ops/conv2d.cc 修改: mindspore/core/ops/logical_and.h 修改: mindspore/core/ops/logical_not.h 修改: mindspore/core/ops/logical_or.h 修改: mindspore/core/ops/reduce_all.h 修改: mindspore/core/ops/reduce_any.h 修改: mindspore/lite/src/runtime/kernel/arm/fp32_grad/sgd.cc 修改: mindspore/nn/layer/quant.py 修改: mindspore/nn/optim/sgd.py 修改: mindspore/nn/sparse/sparse.py 修改: mindspore/numpy/array_creations.py 修改: mindspore/numpy/array_ops.py 修改: mindspore/numpy/logic_ops.py 修改: mindspore/numpy/math_ops.py 修改: mindspore/ops/operations/_inner_ops.py 修改: mindspore/ops/operations/array_ops.py 修改: mindspore/ops/operations/rl_ops.py 修改: mindspore/train/_utils.py 修改: tests/ut/python/model/test_lenet_core_after_exception.py 修改: mindspore/_extends/parse/standard_method.py 修改: mindspore/ops/operations/rl_ops.py 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/core/ops/conv2d.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ctcloss_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/fl/fused_pull_weight_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/fl/fused_push_weight_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/mkldnn/conv2d_grad_filter_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/mkldnn/conv2d_grad_input_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ps/sparse_apply_ftrl_ps_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ps/sparse_apply_lazy_adam_ps_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/rolling_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/scatter_arithmetic_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/split_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/update_cache_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/split_gpu_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/math/broadcast_gpu_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/nn/conv2d_grad_input_gpu_kernel.h 修改: mindspore/ccsrc/fl/server/server.cc 修改: mindspore/ccsrc/frontend/optimizer/ad/kpynative.cc 修改: mindspore/ccsrc/frontend/optimizer/irpass/incorporate_getitem.h 修改: mindspore/ccsrc/frontend/optimizer/irpass/inline.h 修改: mindspore/ccsrc/minddata/dataset/core/device_tensor.cc 修改: mindspore/ccsrc/minddata/dataset/core/tensor.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/mnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/qmnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/dataset_node.cc 修改: mindspore/ccsrc/minddata/dataset/engine/opt/pre/epoch_ctrl_pass.cc 修改: mindspore/ccsrc/minddata/dataset/kernels/image/lite_image_utils.cc 修改: mindspore/ccsrc/pipeline/jit/action.cc 修改: mindspore/ccsrc/pipeline/jit/static_analysis/evaluator.cc 修改: mindspore/ccsrc/runtime/device/ascend/executor/tiling/op_tiling_adapter.cc 修改: mindspore/compression/quant/quant_utils.py 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/dataset/engine/validators.py 修改: mindspore/lite/micro/coder/opcoders/nnacl/fp32/affine_fp32_coder.cc 修改: mindspore/lite/micro/coder/opcoders/nnacl/int8/affine_int8_coder.cc 修改: mindspore/lite/src/runtime/kernel/ascend310/src/custom_kernel.cc 修改: mindspore/lite/src/runtime/kernel/opencl/kernel/matmul.cc 修改: mindspore/lite/src/runtime/kernel/opencl/kernel/strassen.cc 修改: mindspore/lite/tools/common/graph_util.h 修改: mindspore/lite/tools/optimizer/fisson/fisson_util.cc 修改: mindspore/ops/composite/math_ops.py 修改: mindspore/ops/operations/_inner_ops.py 修改: mindspore/ops/operations/array_ops.py 修改: mindspore/ops/operations/math_ops.py 修改: mindspore/ops/operations/other_ops.py 修改: mindspore/boost/boost_cell_wrapper.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/update_cache_cpu_kernel.cc 修改: mindspore/ccsrc/common/trans.cc 修改: mindspore/ccsrc/frontend/parallel/cache_embedding/cache_embedding.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/gather_info.cc 修改: mindspore/lite/src/common/log_util.h 修改: mindspore/nn/wrap/loss_scale.py 修改: mindspore/parallel/nn/moe.py 修改: tests/mindspore_test_framework/mindspore_test.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/split_cpu_kernel.cc 修改: mindspore/lite/tools/common/graph_util.h 修改: mindspore/ccsrc/frontend/parallel/ops_info/gather_info.cc 修改: mindspore/core/ops/conv2d.cc 修改: tests/ut/python/model/test_lenet_core_after_exception.py
4 years ago
optimize the comment and log description 修改: ops/operations/_inner_ops.py 修改: ops/operations/_quant_ops.py 修改: ops/operations/array_ops.py 修改: ops/operations/comm_ops.py 修改: ops/operations/math_ops.py 修改: ops/operations/quantum_ops.py 修改: ops/operations/rl_ops.py 修改: ops/operations/sponge_ops.py 修改: ops/operations/sponge_update_ops.py 修改: train/__init__.py 修改: common/tensor.py 修改: train/serialization.py 修改: ccsrc/pipeline/jit/parse/parse.h 修改: explainer/benchmark/_attribution/metric.py 修改: ops/composite/multitype_ops/_constexpr_utils.py 修改: ops/operations/comm_ops.py 修改: RELEASE.md 修改: mindspore/_extends/parse/standard_method.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/concat_offset_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/dynamic_shape_cpu_kernel.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/reshape_info.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/tile_info.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/transpose_info.cc 修改: mindspore/ccsrc/frontend/parallel/strategy.h 修改: mindspore/common/tensor.py 修改: mindspore/core/abstract/prim_arrays.cc 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/core/ops/conv2d.cc 修改: mindspore/core/ops/logical_and.h 修改: mindspore/core/ops/logical_not.h 修改: mindspore/core/ops/logical_or.h 修改: mindspore/core/ops/reduce_all.h 修改: mindspore/core/ops/reduce_any.h 修改: mindspore/lite/src/runtime/kernel/arm/fp32_grad/sgd.cc 修改: mindspore/nn/layer/quant.py 修改: mindspore/nn/optim/sgd.py 修改: mindspore/nn/sparse/sparse.py 修改: mindspore/numpy/array_creations.py 修改: mindspore/numpy/array_ops.py 修改: mindspore/numpy/logic_ops.py 修改: mindspore/numpy/math_ops.py 修改: mindspore/ops/operations/_inner_ops.py 修改: mindspore/ops/operations/array_ops.py 修改: mindspore/ops/operations/rl_ops.py 修改: mindspore/train/_utils.py 修改: tests/ut/python/model/test_lenet_core_after_exception.py 修改: mindspore/_extends/parse/standard_method.py 修改: mindspore/ops/operations/rl_ops.py 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/core/ops/conv2d.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ctcloss_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/fl/fused_pull_weight_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/fl/fused_push_weight_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/mkldnn/conv2d_grad_filter_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/mkldnn/conv2d_grad_input_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ps/sparse_apply_ftrl_ps_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ps/sparse_apply_lazy_adam_ps_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/rolling_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/scatter_arithmetic_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/split_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/update_cache_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/split_gpu_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/math/broadcast_gpu_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/nn/conv2d_grad_input_gpu_kernel.h 修改: mindspore/ccsrc/fl/server/server.cc 修改: mindspore/ccsrc/frontend/optimizer/ad/kpynative.cc 修改: mindspore/ccsrc/frontend/optimizer/irpass/incorporate_getitem.h 修改: mindspore/ccsrc/frontend/optimizer/irpass/inline.h 修改: mindspore/ccsrc/minddata/dataset/core/device_tensor.cc 修改: mindspore/ccsrc/minddata/dataset/core/tensor.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/mnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/qmnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/dataset_node.cc 修改: mindspore/ccsrc/minddata/dataset/engine/opt/pre/epoch_ctrl_pass.cc 修改: mindspore/ccsrc/minddata/dataset/kernels/image/lite_image_utils.cc 修改: mindspore/ccsrc/pipeline/jit/action.cc 修改: mindspore/ccsrc/pipeline/jit/static_analysis/evaluator.cc 修改: mindspore/ccsrc/runtime/device/ascend/executor/tiling/op_tiling_adapter.cc 修改: mindspore/compression/quant/quant_utils.py 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/dataset/engine/validators.py 修改: mindspore/lite/micro/coder/opcoders/nnacl/fp32/affine_fp32_coder.cc 修改: mindspore/lite/micro/coder/opcoders/nnacl/int8/affine_int8_coder.cc 修改: mindspore/lite/src/runtime/kernel/ascend310/src/custom_kernel.cc 修改: mindspore/lite/src/runtime/kernel/opencl/kernel/matmul.cc 修改: mindspore/lite/src/runtime/kernel/opencl/kernel/strassen.cc 修改: mindspore/lite/tools/common/graph_util.h 修改: mindspore/lite/tools/optimizer/fisson/fisson_util.cc 修改: mindspore/ops/composite/math_ops.py 修改: mindspore/ops/operations/_inner_ops.py 修改: mindspore/ops/operations/array_ops.py 修改: mindspore/ops/operations/math_ops.py 修改: mindspore/ops/operations/other_ops.py 修改: mindspore/boost/boost_cell_wrapper.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/update_cache_cpu_kernel.cc 修改: mindspore/ccsrc/common/trans.cc 修改: mindspore/ccsrc/frontend/parallel/cache_embedding/cache_embedding.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/gather_info.cc 修改: mindspore/lite/src/common/log_util.h 修改: mindspore/nn/wrap/loss_scale.py 修改: mindspore/parallel/nn/moe.py 修改: tests/mindspore_test_framework/mindspore_test.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/split_cpu_kernel.cc 修改: mindspore/lite/tools/common/graph_util.h 修改: mindspore/ccsrc/frontend/parallel/ops_info/gather_info.cc 修改: mindspore/core/ops/conv2d.cc 修改: tests/ut/python/model/test_lenet_core_after_exception.py
4 years ago
optimize the comment and log description 修改: ops/operations/_inner_ops.py 修改: ops/operations/_quant_ops.py 修改: ops/operations/array_ops.py 修改: ops/operations/comm_ops.py 修改: ops/operations/math_ops.py 修改: ops/operations/quantum_ops.py 修改: ops/operations/rl_ops.py 修改: ops/operations/sponge_ops.py 修改: ops/operations/sponge_update_ops.py 修改: train/__init__.py 修改: common/tensor.py 修改: train/serialization.py 修改: ccsrc/pipeline/jit/parse/parse.h 修改: explainer/benchmark/_attribution/metric.py 修改: ops/composite/multitype_ops/_constexpr_utils.py 修改: ops/operations/comm_ops.py 修改: RELEASE.md 修改: mindspore/_extends/parse/standard_method.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/concat_offset_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/dynamic_shape_cpu_kernel.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/reshape_info.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/tile_info.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/transpose_info.cc 修改: mindspore/ccsrc/frontend/parallel/strategy.h 修改: mindspore/common/tensor.py 修改: mindspore/core/abstract/prim_arrays.cc 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/core/ops/conv2d.cc 修改: mindspore/core/ops/logical_and.h 修改: mindspore/core/ops/logical_not.h 修改: mindspore/core/ops/logical_or.h 修改: mindspore/core/ops/reduce_all.h 修改: mindspore/core/ops/reduce_any.h 修改: mindspore/lite/src/runtime/kernel/arm/fp32_grad/sgd.cc 修改: mindspore/nn/layer/quant.py 修改: mindspore/nn/optim/sgd.py 修改: mindspore/nn/sparse/sparse.py 修改: mindspore/numpy/array_creations.py 修改: mindspore/numpy/array_ops.py 修改: mindspore/numpy/logic_ops.py 修改: mindspore/numpy/math_ops.py 修改: mindspore/ops/operations/_inner_ops.py 修改: mindspore/ops/operations/array_ops.py 修改: mindspore/ops/operations/rl_ops.py 修改: mindspore/train/_utils.py 修改: tests/ut/python/model/test_lenet_core_after_exception.py 修改: mindspore/_extends/parse/standard_method.py 修改: mindspore/ops/operations/rl_ops.py 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/core/ops/conv2d.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ctcloss_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/fl/fused_pull_weight_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/fl/fused_push_weight_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/mkldnn/conv2d_grad_filter_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/mkldnn/conv2d_grad_input_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ps/sparse_apply_ftrl_ps_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ps/sparse_apply_lazy_adam_ps_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/rolling_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/scatter_arithmetic_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/split_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/update_cache_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/split_gpu_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/math/broadcast_gpu_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/nn/conv2d_grad_input_gpu_kernel.h 修改: mindspore/ccsrc/fl/server/server.cc 修改: mindspore/ccsrc/frontend/optimizer/ad/kpynative.cc 修改: mindspore/ccsrc/frontend/optimizer/irpass/incorporate_getitem.h 修改: mindspore/ccsrc/frontend/optimizer/irpass/inline.h 修改: mindspore/ccsrc/minddata/dataset/core/device_tensor.cc 修改: mindspore/ccsrc/minddata/dataset/core/tensor.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/mnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/qmnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/dataset_node.cc 修改: mindspore/ccsrc/minddata/dataset/engine/opt/pre/epoch_ctrl_pass.cc 修改: mindspore/ccsrc/minddata/dataset/kernels/image/lite_image_utils.cc 修改: mindspore/ccsrc/pipeline/jit/action.cc 修改: mindspore/ccsrc/pipeline/jit/static_analysis/evaluator.cc 修改: mindspore/ccsrc/runtime/device/ascend/executor/tiling/op_tiling_adapter.cc 修改: mindspore/compression/quant/quant_utils.py 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/dataset/engine/validators.py 修改: mindspore/lite/micro/coder/opcoders/nnacl/fp32/affine_fp32_coder.cc 修改: mindspore/lite/micro/coder/opcoders/nnacl/int8/affine_int8_coder.cc 修改: mindspore/lite/src/runtime/kernel/ascend310/src/custom_kernel.cc 修改: mindspore/lite/src/runtime/kernel/opencl/kernel/matmul.cc 修改: mindspore/lite/src/runtime/kernel/opencl/kernel/strassen.cc 修改: mindspore/lite/tools/common/graph_util.h 修改: mindspore/lite/tools/optimizer/fisson/fisson_util.cc 修改: mindspore/ops/composite/math_ops.py 修改: mindspore/ops/operations/_inner_ops.py 修改: mindspore/ops/operations/array_ops.py 修改: mindspore/ops/operations/math_ops.py 修改: mindspore/ops/operations/other_ops.py 修改: mindspore/boost/boost_cell_wrapper.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/update_cache_cpu_kernel.cc 修改: mindspore/ccsrc/common/trans.cc 修改: mindspore/ccsrc/frontend/parallel/cache_embedding/cache_embedding.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/gather_info.cc 修改: mindspore/lite/src/common/log_util.h 修改: mindspore/nn/wrap/loss_scale.py 修改: mindspore/parallel/nn/moe.py 修改: tests/mindspore_test_framework/mindspore_test.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/split_cpu_kernel.cc 修改: mindspore/lite/tools/common/graph_util.h 修改: mindspore/ccsrc/frontend/parallel/ops_info/gather_info.cc 修改: mindspore/core/ops/conv2d.cc 修改: tests/ut/python/model/test_lenet_core_after_exception.py
4 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
optimize the comment and log description 修改: ops/operations/_inner_ops.py 修改: ops/operations/_quant_ops.py 修改: ops/operations/array_ops.py 修改: ops/operations/comm_ops.py 修改: ops/operations/math_ops.py 修改: ops/operations/quantum_ops.py 修改: ops/operations/rl_ops.py 修改: ops/operations/sponge_ops.py 修改: ops/operations/sponge_update_ops.py 修改: train/__init__.py 修改: common/tensor.py 修改: train/serialization.py 修改: ccsrc/pipeline/jit/parse/parse.h 修改: explainer/benchmark/_attribution/metric.py 修改: ops/composite/multitype_ops/_constexpr_utils.py 修改: ops/operations/comm_ops.py 修改: RELEASE.md 修改: mindspore/_extends/parse/standard_method.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/concat_offset_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/dynamic_shape_cpu_kernel.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/reshape_info.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/tile_info.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/transpose_info.cc 修改: mindspore/ccsrc/frontend/parallel/strategy.h 修改: mindspore/common/tensor.py 修改: mindspore/core/abstract/prim_arrays.cc 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/core/ops/conv2d.cc 修改: mindspore/core/ops/logical_and.h 修改: mindspore/core/ops/logical_not.h 修改: mindspore/core/ops/logical_or.h 修改: mindspore/core/ops/reduce_all.h 修改: mindspore/core/ops/reduce_any.h 修改: mindspore/lite/src/runtime/kernel/arm/fp32_grad/sgd.cc 修改: mindspore/nn/layer/quant.py 修改: mindspore/nn/optim/sgd.py 修改: mindspore/nn/sparse/sparse.py 修改: mindspore/numpy/array_creations.py 修改: mindspore/numpy/array_ops.py 修改: mindspore/numpy/logic_ops.py 修改: mindspore/numpy/math_ops.py 修改: mindspore/ops/operations/_inner_ops.py 修改: mindspore/ops/operations/array_ops.py 修改: mindspore/ops/operations/rl_ops.py 修改: mindspore/train/_utils.py 修改: tests/ut/python/model/test_lenet_core_after_exception.py 修改: mindspore/_extends/parse/standard_method.py 修改: mindspore/ops/operations/rl_ops.py 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/core/ops/conv2d.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ctcloss_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/fl/fused_pull_weight_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/fl/fused_push_weight_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/mkldnn/conv2d_grad_filter_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/mkldnn/conv2d_grad_input_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ps/sparse_apply_ftrl_ps_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/ps/sparse_apply_lazy_adam_ps_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/rolling_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/scatter_arithmetic_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/split_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/update_cache_cpu_kernel.cc 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/split_gpu_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/math/broadcast_gpu_kernel.h 修改: mindspore/ccsrc/backend/kernel_compiler/gpu/nn/conv2d_grad_input_gpu_kernel.h 修改: mindspore/ccsrc/fl/server/server.cc 修改: mindspore/ccsrc/frontend/optimizer/ad/kpynative.cc 修改: mindspore/ccsrc/frontend/optimizer/irpass/incorporate_getitem.h 修改: mindspore/ccsrc/frontend/optimizer/irpass/inline.h 修改: mindspore/ccsrc/minddata/dataset/core/device_tensor.cc 修改: mindspore/ccsrc/minddata/dataset/core/tensor.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/mnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/datasetops/source/qmnist_op.cc 修改: mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/dataset_node.cc 修改: mindspore/ccsrc/minddata/dataset/engine/opt/pre/epoch_ctrl_pass.cc 修改: mindspore/ccsrc/minddata/dataset/kernels/image/lite_image_utils.cc 修改: mindspore/ccsrc/pipeline/jit/action.cc 修改: mindspore/ccsrc/pipeline/jit/static_analysis/evaluator.cc 修改: mindspore/ccsrc/runtime/device/ascend/executor/tiling/op_tiling_adapter.cc 修改: mindspore/compression/quant/quant_utils.py 修改: mindspore/core/abstract/prim_nn.cc 修改: mindspore/dataset/engine/validators.py 修改: mindspore/lite/micro/coder/opcoders/nnacl/fp32/affine_fp32_coder.cc 修改: mindspore/lite/micro/coder/opcoders/nnacl/int8/affine_int8_coder.cc 修改: mindspore/lite/src/runtime/kernel/ascend310/src/custom_kernel.cc 修改: mindspore/lite/src/runtime/kernel/opencl/kernel/matmul.cc 修改: mindspore/lite/src/runtime/kernel/opencl/kernel/strassen.cc 修改: mindspore/lite/tools/common/graph_util.h 修改: mindspore/lite/tools/optimizer/fisson/fisson_util.cc 修改: mindspore/ops/composite/math_ops.py 修改: mindspore/ops/operations/_inner_ops.py 修改: mindspore/ops/operations/array_ops.py 修改: mindspore/ops/operations/math_ops.py 修改: mindspore/ops/operations/other_ops.py 修改: mindspore/boost/boost_cell_wrapper.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/update_cache_cpu_kernel.cc 修改: mindspore/ccsrc/common/trans.cc 修改: mindspore/ccsrc/frontend/parallel/cache_embedding/cache_embedding.cc 修改: mindspore/ccsrc/frontend/parallel/ops_info/gather_info.cc 修改: mindspore/lite/src/common/log_util.h 修改: mindspore/nn/wrap/loss_scale.py 修改: mindspore/parallel/nn/moe.py 修改: tests/mindspore_test_framework/mindspore_test.py 修改: mindspore/ccsrc/backend/kernel_compiler/cpu/split_cpu_kernel.cc 修改: mindspore/lite/tools/common/graph_util.h 修改: mindspore/ccsrc/frontend/parallel/ops_info/gather_info.cc 修改: mindspore/core/ops/conv2d.cc 修改: tests/ut/python/model/test_lenet_core_after_exception.py
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503
  1. # Copyright 2020-2021 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. """array operations, the function docs are adapted from Numpy API."""
  16. import math
  17. import operator
  18. import numpy as onp
  19. from ..common import Tensor
  20. from ..common import dtype as mstype
  21. from ..ops import operations as P
  22. from ..ops import functional as F
  23. from ..ops.primitive import constexpr
  24. from ..nn.layer.basic import tril as nn_tril
  25. from ..nn.layer.basic import triu as nn_triu
  26. from .._c_expression import Tensor as Tensor_
  27. from .utils import _check_input_for_asarray, _deep_list, _deep_tensor_to_nparray, \
  28. _check_input_tensor, _convert_64_to_32, _get_dtype_from_scalar, \
  29. _expand, _to_tensor, _slice_along_axis, _callable
  30. from .utils_const import _raise_value_error, _empty, _max, _min, \
  31. _check_same_type, _is_shape_empty, _check_shape, _check_dtype, _tile_size, _abs, \
  32. _raise_type_error, _expanded_shape, _check_is_float, _iota, _type_convert, \
  33. _canonicalize_axis, _list_comprehensions, _ceil, _tuple_slice, _raise_unimplemented_error, \
  34. _tuple_setitem
  35. from .array_ops import ravel, concatenate, broadcast_arrays, reshape, broadcast_to, flip, \
  36. apply_along_axis, where, moveaxis
  37. from .dtypes import nan, pi
  38. # According to official numpy reference, the dimension of a numpy array must be less
  39. # than 32
  40. MAX_NUMPY_DIMS = 32
  41. # All types that can be accepted as "array_like" parameters in graph mode.
  42. ARRAY_TYPES = (int, float, bool, list, tuple, Tensor)
  43. _reduce_min_keepdims = P.ReduceMin(True)
  44. _reduce_max_keepdims = P.ReduceMax(True)
  45. _reduce_mean_keepdims = P.ReduceMean(True)
  46. def array(obj, dtype=None, copy=True, ndmin=0):
  47. """
  48. Creates a tensor.
  49. This function creates tensors from an array-like object.
  50. Args:
  51. obj (Union[int, float, bool, list, tuple]): Input data, in any form that
  52. can be converted to a `Tensor`. This includes Tensor, list, tuple and numbers.
  53. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, can
  54. be in format of np.int32, or \'int32\'. If dtype is :class:`None`, the data type
  55. of the new tensor will be inferred from obj. Default is :class:`None`.
  56. copy (bool): If `True`, then the object is copied. Otherwise, a copy will
  57. only be made if necessary. Default: `True`.
  58. ndmin (int): Specifies the minimum number of dimensions that the resulting
  59. tensor should have. Ones will be pre-pended to the shape as needed to
  60. meet this requirement. Default: 0
  61. Returns:
  62. Tensor, generated tensor with the specified dtype.
  63. Raises:
  64. TypeError: If input arguments have types not specified above.
  65. ValueError: If input `obj` has different sizes at different dimensions.
  66. Supported Platforms:
  67. ``Ascend`` ``GPU`` ``CPU``
  68. Examples:
  69. >>> import mindspore.numpy as np
  70. >>> print(np.array([1,2,3]))
  71. [1 2 3]
  72. """
  73. if dtype is not None:
  74. dtype = _check_dtype(dtype)
  75. res = asarray(obj, dtype)
  76. if ndmin > res.ndim:
  77. if res.size == 0:
  78. _raise_value_error("Empty tensor cannot be expanded beyond the current dimension.")
  79. res = _expand(res, ndmin)
  80. if copy and isinstance(obj, Tensor):
  81. res = copy_(res)
  82. elif dtype is not None and dtype != res.dtype:
  83. res = res.astype(dtype)
  84. return res
  85. @constexpr
  86. def asarray_const(a, dtype=None):
  87. """Converts the input to tensor. Note here `a` cannot be tensor itself."""
  88. _check_input_for_asarray(a)
  89. if dtype is not None:
  90. dtype = _check_dtype(dtype)
  91. if isinstance(a, (float, int, bool)) and dtype is None:
  92. dtype = _get_dtype_from_scalar(a)
  93. if isinstance(a, (list, tuple)):
  94. # Convert all tuple/nested tuples to lists
  95. a = _deep_list(a)
  96. # Convert all tensor sub-elements to numpy arrays
  97. a = _deep_tensor_to_nparray(a)
  98. a = onp.asarray(a)
  99. if a.dtype is onp.dtype('object'):
  100. raise ValueError('Input array must have the same size across all dimensions.')
  101. # If dtype is not specified, we keep consistent with numpy decision
  102. # only exceptions are: we use int/float32
  103. if dtype is None:
  104. dtype = mstype.pytype_to_dtype(a.dtype)
  105. if dtype == mstype.float64:
  106. dtype = mstype.float32
  107. elif dtype == mstype.int64:
  108. dtype = mstype.int32
  109. if isinstance(a, onp.ndarray) and dtype is None:
  110. if a.dtype is onp.dtype('object'):
  111. raise TypeError(f"For Tensor conversion, the input_data is {a} that contains unsupported element.")
  112. dtype = mstype.pytype_to_dtype(a.dtype)
  113. a = Tensor.from_numpy(a)
  114. return Tensor(a, dtype=dtype)
  115. def asarray(a, dtype=None):
  116. """
  117. Converts the input to tensor.
  118. This function converts tensors from an array-like object.
  119. Args:
  120. a (Union[int, float, bool, list, tuple, Tensor]): Input data, in any form that can
  121. be converted to a `Tensor`. This includes Tensor, list, tuple and numbers.
  122. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, can
  123. be in format of np.int32, or \'int32\'. If dtype is :class:`None`, the data type
  124. of the new tensor will be inferred from obj. Default is :class:`None`.
  125. Returns:
  126. Tensor, generated tensor with the specified dtype.
  127. Raises:
  128. TypeError: If input arguments have types not specified above.
  129. ValueError: If input `a` has different sizes at different dimensions.
  130. Supported Platforms:
  131. ``Ascend`` ``GPU`` ``CPU``
  132. Examples:
  133. >>> import mindspore.numpy as np
  134. >>> print(np.asarray([1,2,3]))
  135. [1 2 3]
  136. """
  137. if dtype is not None:
  138. dtype = _check_dtype(dtype)
  139. if isinstance(a, Tensor):
  140. if dtype is None or dtype == a.dtype:
  141. return a
  142. return a.astype(dtype)
  143. return asarray_const(a, dtype)
  144. @constexpr
  145. def asfarray_const(a, dtype=mstype.float32):
  146. """Converts the input to tensor. Note here `a` cannot be tensor itself."""
  147. _check_input_for_asarray(a)
  148. if isinstance(a, (list, tuple)):
  149. # Convert all tuple/nested tuples to lists
  150. a = _deep_list(a)
  151. # Convert all tensor sub-elements to numpy arrays
  152. a = _deep_tensor_to_nparray(a)
  153. a = onp.asarray(a)
  154. if a.dtype is onp.dtype('object'):
  155. raise ValueError(f"For Tensor conversion, the input_data is {a} that contains unsupported element.")
  156. a = Tensor.from_numpy(a)
  157. return Tensor(a, dtype)
  158. def asfarray(a, dtype=mstype.float32):
  159. """
  160. Similar to asarray, converts the input to a float tensor.
  161. If non-float dtype is defined, this function will return a float32 tensor instead.
  162. Args:
  163. a (Union[int, float, bool, list, tuple, Tensor]): Input data, in any form that can
  164. be converted to a `Tensor`. This includes Tensor, list, tuple and numbers.
  165. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, can
  166. be in format of np.int32, or \'int32\'. If dtype is :class:`None`, the data type
  167. of the new tensor will be inferred from `a`. Default is :class:`mindspore.float32`.
  168. Returns:
  169. Tensor, generated tensor with the specified float dtype.
  170. Raises:
  171. TypeError: If input arguments have types not specified above.
  172. ValueError: If input `a` has different sizes at different dimensions.
  173. Supported Platforms:
  174. ``Ascend`` ``GPU`` ``CPU``
  175. Examples:
  176. >>> import mindspore.numpy as np
  177. >>> print(np.asfarray([1,2,3]))
  178. [1. 2. 3.]
  179. """
  180. if dtype is None:
  181. return asarray(a)
  182. dtype = _check_dtype(dtype)
  183. if dtype not in (mstype.float16, mstype.float32, mstype.float64):
  184. dtype = mstype.float32
  185. if isinstance(a, Tensor):
  186. return a.astype(dtype)
  187. return asfarray_const(a, dtype)
  188. def copy_(a):
  189. """
  190. Returns a tensor copy of the given object.
  191. Args:
  192. a (Union[int, float, bool, list, tuple, Tensor]): Input data, in any form that can
  193. be converted to a Tensor. This includes Tensor, list, tuple and numbers.
  194. Returns:
  195. Tensor, has the same data as `a`.
  196. Raises:
  197. TypeError: If input `a` has type not specified above.
  198. ValueError: If input `a` has different sizes at different dimensions.
  199. Supported Platforms:
  200. ``Ascend`` ``GPU`` ``CPU``
  201. Examples:
  202. >>> import mindspore.numpy as np
  203. >>> x = np.ones((2,2))
  204. >>> print(np.copy(x))
  205. [[1. 1.]
  206. [1. 1.]]
  207. """
  208. a = asarray(a)
  209. return a.copy()
  210. def ones(shape, dtype=mstype.float32):
  211. """
  212. Returns a new tensor of given shape and type, filled with ones.
  213. Args:
  214. shape (Union[int, tuple, list]): the shape of the new tensor.
  215. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
  216. Default is :class:`mstype.float32`.
  217. Returns:
  218. Tensor, with the designated `shape` and `dtype`, filled with ones.
  219. Raises:
  220. TypeError: If input arguments have types not specified above.
  221. ValueError: If `shape` entries have values :math:`< 0`.
  222. Supported Platforms:
  223. ``Ascend`` ``GPU`` ``CPU``
  224. Examples:
  225. >>> import mindspore.numpy as np
  226. >>> print(np.ones((2,2)))
  227. [[1. 1.]
  228. [1. 1.]]
  229. """
  230. shape = _check_shape(shape)
  231. dtype = _check_dtype(dtype)
  232. if _is_shape_empty(shape):
  233. return full(shape, 1.0, dtype)
  234. output = F.fill(dtype, shape, 1)
  235. return output
  236. def zeros(shape, dtype=mstype.float32):
  237. """
  238. Returns a new tensor of given shape and type, filled with zeros.
  239. Args:
  240. shape (Union[int, tuple, list]): the shape of the new tensor.
  241. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
  242. Default is :class:`mstype.float32`.
  243. Returns:
  244. Tensor, with the designated `shape` and `dtype`, filled with zeros.
  245. Raises:
  246. TypeError: If input arguments have types not specified above.
  247. ValueError: If `shape` entries have values :math:`< 0`.
  248. Supported Platforms:
  249. ``Ascend`` ``GPU`` ``CPU``
  250. Examples:
  251. >>> import mindspore.numpy as np
  252. >>> print(np.zeros((2,2)))
  253. [[0. 0.]
  254. [0. 0.]]
  255. """
  256. shape = _check_shape(shape)
  257. dtype = _check_dtype(dtype)
  258. if _is_shape_empty(shape):
  259. return full(shape, 0.0, dtype)
  260. output = F.fill(dtype, shape, 0)
  261. return output
  262. def full(shape, fill_value, dtype=None):
  263. """
  264. Returns a new tensor of given shape and type, filled with `fill_value`.
  265. Args:
  266. shape (Union[int, tuple(int), list(int)]): Shape of the new tensor, e.g.,
  267. :math:`(2, 3)` or :math:`2`.
  268. fill_value (Union[int, float, bool, list, tuple]): Scalar or array_like
  269. fill value.
  270. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype,
  271. if `dtype` is :class:`None`, the data type of the new tensor will be inferred from
  272. `fill_value`. Default is :class:`None`.
  273. Returns:
  274. Tensor, with the designated shape and dtype, filled with `fill_value`.
  275. Raises:
  276. TypeError: If input arguments have types not specified above.
  277. ValueError: If `shape` has entries < 0.
  278. Supported Platforms:
  279. ``Ascend`` ``GPU`` ``CPU``
  280. Examples:
  281. >>> import mindspore.numpy as np
  282. >>> print(np.full((2,2), True))
  283. [[True True]
  284. [True True]]
  285. """
  286. shape = _check_shape(shape)
  287. if not isinstance(fill_value, ARRAY_TYPES):
  288. _raise_type_error("fill value should be int, float, bool, list, tuple, Tensor, but got", fill_value)
  289. if dtype is not None:
  290. dtype = _check_dtype(dtype)
  291. else:
  292. if isinstance(fill_value, (int, float, bool)):
  293. dtype = _get_dtype_from_scalar(fill_value)
  294. if isinstance(fill_value, Tensor):
  295. dtype = fill_value.dtype
  296. if not _is_shape_empty(shape):
  297. if isinstance(fill_value, (int, float, bool)):
  298. return F.fill(dtype, shape, fill_value)
  299. if isinstance(fill_value, (list, tuple)):
  300. fill_value = asarray_const(fill_value)
  301. return broadcast_to(fill_value, shape)
  302. # if shape contains zero, use c.Tensor()
  303. return _convert_64_to_32(empty_compile(dtype, shape))
  304. def arange(start, stop=None, step=None, dtype=None):
  305. """
  306. Returns evenly spaced values within a given interval.
  307. Args:
  308. start(Union[int, float]): Start of interval. The interval includes this value.
  309. When `stop` is provided as a position argument, `start` must be given, when `stop`
  310. is a normal argument, `start` can be optional, and default is 0.
  311. Please see additional examples below.
  312. stop(Union[int, float], optional): End of interval. The interval does not
  313. include this value, except in some cases where `step` is not an integer
  314. and floating point round-off affects the length of out.
  315. step(Union[int, float], optional): Spacing between values. For any output
  316. `out`, this is the distance between two adjacent values, :math:`out[i+1] - out[i]`.
  317. The default step size is 1. If `step` is specified as a position argument,
  318. `start` must also be given.
  319. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
  320. If dtype is None, the data type of the new tensor will be inferred from start,
  321. stop and step. Default is None.
  322. Returns:
  323. Tensor with evenly spaced values.
  324. Raises:
  325. TypeError(PyNative Mode): If input arguments have types not specified above,
  326. or arguments are not given in the correct orders specified above.
  327. RuntimeError(Graph Mode): The inputs that lead to TypeError in Pynative Mode
  328. will lead to RuntimeError in Graph Mode.
  329. Supported Platforms:
  330. ``Ascend`` ``GPU`` ``CPU``
  331. Examples:
  332. >>> import mindspore.numpy as np
  333. >>> print(np.arange(0, 5, 1))
  334. [0 1 2 3 4]
  335. >>> print(np.arange(3))
  336. [0 1 2]
  337. >>> print(np.arange(start=0, stop=3))
  338. [0 1 2]
  339. >>> print(np.arange(0, stop=3, step=0.5))
  340. [0. 0.5 1. 1.5 2. 2.5]
  341. >>> print(np.arange(stop=3)) # This will lead to TypeError
  342. """
  343. # This implementation was inspired by jax.numpy.arange
  344. # infer the dtype
  345. if dtype is None:
  346. dtype = _get_dtype_from_scalar(start, stop, step)
  347. if stop is None and step is None: # (start, stop, step) -> (0, start, 1)
  348. num = _ceil(start)
  349. out = _iota(mstype.float32, num)
  350. elif step is None: # (start, stop, step) -> (start, stop, 1)
  351. num = _ceil(stop - start)
  352. out = _iota(mstype.float32, num) + start
  353. elif stop is None: # (start, stop, step) -> (0, start, step)
  354. num = _ceil((start + 0.0) / step)
  355. out = _iota(mstype.float32, num) * step
  356. else:
  357. num = _ceil((stop - start + 0.0) / step)
  358. out = _iota(mstype.float32, num) * step + start
  359. return out.astype(dtype)
  360. def _type_checking_for_xspace(start, stop, num, endpoint, dtype):
  361. """utility parameter checking function for linspace, logspace, geomspace."""
  362. if not isinstance(start, ARRAY_TYPES):
  363. _raise_type_error("start should be int, float, bool, list, tuple, Tensor, but got", start)
  364. if not isinstance(stop, ARRAY_TYPES):
  365. _raise_type_error("end should be int, float, bool, list, tuple, Tensor, but got", stop)
  366. if not isinstance(start, Tensor):
  367. start = _type_convert(Tensor, start).astype(mstype.float32)
  368. if not isinstance(stop, Tensor):
  369. stop = _type_convert(Tensor, stop).astype(mstype.float32)
  370. if not isinstance(num, int):
  371. _raise_type_error("num should be an integer, but got ", num)
  372. if not isinstance(endpoint, bool):
  373. _raise_type_error("endpoint should be an boolean, but got ", endpoint)
  374. if dtype is not None:
  375. dtype = _check_dtype(dtype)
  376. else:
  377. dtype = mstype.float32
  378. start, stop = broadcast_arrays(start, stop)
  379. return start, stop, num, endpoint, dtype
  380. def _compute_shapes(start, axis, num, endpoint):
  381. """Computes shapes for local variables for np.linspace"""
  382. bounds_shape = start.shape
  383. bounds_shape = _tuple_slice(bounds_shape, None, axis) + (1,) + _tuple_slice(bounds_shape, axis, None)
  384. iota_shape = _list_comprehensions(start.ndim+1, 1, True)
  385. iota_shape = _tuple_slice(iota_shape, None, axis) + (num,) + _tuple_slice(iota_shape, axis+1, None)
  386. num_tensor = _type_convert(Tensor, num).astype(mstype.float32)
  387. div = (num_tensor - 1) if endpoint else num_tensor
  388. return bounds_shape, iota_shape, div
  389. def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
  390. """
  391. Returns evenly spaced values within a given interval.
  392. Args:
  393. start (Union[int, list(int), tuple(int), tensor]): The starting value of the sequence.
  394. stop (Union[int, list(int), tuple(int), tensor]): The end value of the sequence,
  395. unless `endpoint` is set to False. In that case, the sequence consists
  396. of all but the last of `num + 1` evenly spaced samples, so that `stop`
  397. is excluded. Note that the step size changes when `endpoint` is False.
  398. num (int, optional): Number of samples to generate. Default is 50.
  399. endpoint (bool, optional): If True, `stop` is the last sample. Otherwise, it is
  400. not included. Default is True.
  401. retstep (bool, optional): If True, return (`samples`, `step`), where `step` is
  402. the spacing between samples.
  403. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype,
  404. If `dtype` is None, infer the data type from other input arguments. Default is None.
  405. axis (int, optional): The axis in the result to store the samples. Relevant
  406. only if start or stop are array-like. By default, the samples will
  407. be along a new axis inserted at the beginning. Use -1 to get an axis at the end.
  408. Default is 0.
  409. Returns:
  410. Tensor, with `num` equally spaced samples in the closed interval
  411. :math:`[start, stop]` or the half-open interval :math:`[start, stop)`
  412. (depending on whether `endpoint` is True or False).
  413. Step, the size of spacing between samples, only returned if `retstep` is True.
  414. Raises:
  415. TypeError: If input arguments have types not specified above.
  416. Supported Platforms:
  417. ``Ascend`` ``GPU`` ``CPU``
  418. Examples:
  419. >>> import mindspore.numpy as np
  420. >>> print(np.linspace(0, 5, 6))
  421. [0. 1. 2. 3. 4. 5.]
  422. """
  423. # This implementation was inspired by jax.numpy.linspace and numpy.linspace
  424. start, stop, num, endpoint, dtype = _type_checking_for_xspace(start, stop, num, endpoint, dtype)
  425. axis = _canonicalize_axis(axis, start.ndim+1)
  426. if not isinstance(retstep, bool):
  427. _raise_type_error("retstep should be an boolean, but got ", retstep)
  428. bounds_shape, iota_shape, div = _compute_shapes(start, axis, num, endpoint)
  429. out = None
  430. delta = None
  431. if num > 1:
  432. delta = (stop - start) / div
  433. # This is similar to how numpy and jax compute linspace
  434. start_expand = reshape(start, bounds_shape)
  435. incremental_expand = reshape(_iota(mstype.float32, num), iota_shape)
  436. delta_expand = reshape(delta, bounds_shape)
  437. start_expand, incremental_expand, delta_expand = broadcast_arrays(
  438. start_expand, incremental_expand, delta_expand)
  439. out = start_expand + (incremental_expand * delta_expand)
  440. # recover endpoint
  441. if endpoint:
  442. out = moveaxis(out, axis, 0)
  443. out[-1] = stop
  444. out = moveaxis(out, 0, axis)
  445. elif num == 1:
  446. delta = nan if endpoint else stop - start
  447. out = reshape(start, bounds_shape)
  448. else: # num == 0
  449. _raise_value_error("cannot support Tensor with num=0.")
  450. if retstep:
  451. return out.astype(dtype), delta
  452. return out.astype(dtype)
  453. def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
  454. """
  455. Returns numbers spaced evenly on a log scale.
  456. In linear space, the sequence starts at base ** start (base to the power of
  457. start) and ends with base ** stop (see endpoint below).
  458. Args:
  459. start (Union[int, list(int), tuple(int), tensor]): ``base ** start`` is the starting
  460. value of the sequence.
  461. stop (Union[int, list(int), tuple(int), tensor]): ``base ** stop`` is the final value of
  462. the sequence, unless `endpoint` is False. In that case, ``num + 1`` values are spaced
  463. over the interval in log-space, of which all but the last (a sequence of length num)
  464. are returned.
  465. num (int, optional): Number of samples to generate. Default is 50.
  466. endpoint (bool, optional): If True, `stop` is the last sample. Otherwise, it is
  467. not included. Default is True.
  468. base (Union[int, float], optional): The base of the log space. The step size
  469. between the elements in :math:`ln(samples) / ln(base)` (or :math:`log_{base}(samples)`)
  470. is uniform. Default is 10.0.
  471. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
  472. If `dtype` is None, infer the data type from other input arguments. Default is None.
  473. axis (int, optional): The axis in the result to store the samples. Relevant
  474. only if start or stop is array-like. By default, the samples will
  475. be along a new axis inserted at the beginning. Use -1 to get an axis at the end.
  476. Default is 0.
  477. Returns:
  478. Tensor, equally spaced on a log scale.
  479. Raises:
  480. TypeError: If input arguments have types not specified above.
  481. Supported Platforms:
  482. ``Ascend`` ``GPU`` ``CPU``
  483. Examples:
  484. >>> import mindspore.numpy as np
  485. >>> print(np.logspace(0, 5, 6, base=2.0))
  486. [ 1. 2. 4. 8. 16. 32.]
  487. """
  488. # This implementation was inspired by jax.numpy.linspace and numpy.linspace
  489. start, stop, num, endpoint, dtype = _type_checking_for_xspace(start, stop, num, endpoint, dtype)
  490. axis = _canonicalize_axis(axis, start.ndim+1)
  491. if not isinstance(base, (int, float, bool)):
  492. _raise_type_error("base should be a number, but got ", base)
  493. linspace_res = linspace(start, stop, num, endpoint=endpoint, retstep=False, dtype=None, axis=axis)
  494. return F.tensor_pow(base, linspace_res).astype(dtype)
  495. def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):
  496. """
  497. Returns numbers spaced evenly on a log scale (a geometric progression).
  498. This is similar to logspace, but with endpoints specified directly. Each output sample
  499. is a constant multiple of the previous.
  500. Args:
  501. start (Union[int, list(int), tuple(int), tensor]): The starting value of the sequence.
  502. stop (Union[int, list(int), tuple(int), tensor]): The final value of the sequence,
  503. unless endpoint is False. In that case, num + 1 values are spaced over the
  504. interval in log-space, of which all but the last (a sequence of length num) are
  505. returned.
  506. num (int, optional): Number of samples to generate. Default is 50.
  507. endpoint (bool, optional): If True, `stop` is the last sample. Otherwise, it is
  508. not included. Default is True.
  509. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, can
  510. be in format of np.float32, or `float32`.If `dtype` is None, infer the data
  511. type from other input arguments. Default is None.
  512. axis (int, optional): The axis in the result to store the samples. Relevant
  513. only if start or stop is array-like. By default (0), the samples will
  514. be along a new axis inserted at the beginning. Use -1 to get an axis at the end.
  515. Default is 0.
  516. Returns:
  517. Tensor, with samples equally spaced on a log scale.
  518. Raises:
  519. TypeError: If input arguments have types not specified above.
  520. Supported Platforms:
  521. ``Ascend`` ``GPU`` ``CPU``
  522. Examples:
  523. >>> output = np.geomspace(1, 256, num=9)
  524. >>> print(output)
  525. [ 1. 2. 4. 8. 16. 32. 64. 128. 256.]
  526. >>> output = np.geomspace(1, 256, num=8, endpoint=False)
  527. >>> print(output)
  528. [ 1. 2. 4. 8. 16. 32. 64. 128.]
  529. """
  530. start, stop, num, endpoint, dtype = _type_checking_for_xspace(start, stop, num, endpoint, dtype)
  531. axis = _canonicalize_axis(axis, start.ndim+1)
  532. root = num
  533. if endpoint:
  534. root -= 1
  535. bases = F.tensor_pow(F.tensor_div(stop, start), asarray_const(1./(root)))
  536. exponents = linspace(zeros(F.shape(bases)), F.fill(F.dtype(bases), F.shape(bases), root),
  537. num, endpoint=endpoint, dtype=dtype, axis=axis)
  538. shape = F.shape(bases)
  539. axis = axis + F.rank(bases) + 1 if axis < 0 else axis
  540. expanded_shape = _tuple_slice(shape, None, axis) + (1,) + _tuple_slice(shape, axis, None)
  541. bases = F.reshape(bases, expanded_shape)
  542. start = F.reshape(start, expanded_shape)
  543. res = F.tensor_mul(F.tensor_pow(bases, exponents), start)
  544. if dtype is not None:
  545. res = F.cast(res, dtype)
  546. return res
  547. def eye(N, M=None, k=0, dtype=mstype.float32):
  548. """
  549. Returns a 2-D tensor with ones on the diagonal and zeros elsewhere.
  550. Args:
  551. N (int): Number of rows in the output, must be larger than 0.
  552. M (int, optional): Number of columns in the output. If is :class:`None`, defaults to `N`,
  553. if defined, must be larger than 0. Deault is :class:`None`.
  554. k (int, optional): Index of the diagonal: 0 (the default) refers to the main
  555. diagonal, a positive value refers to an upper diagonal, and a negative value
  556. to a lower diagonal. Default is 0.
  557. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
  558. Default is mstype.float32.
  559. Returns:
  560. A tensor of shape (N, M). A tensor where all elements are equal to zero,
  561. except for the k-th diagonal, whose values are equal to one.
  562. Raises:
  563. TypeError: If input arguments have types not specified above.
  564. Supported Platforms:
  565. ``Ascend`` ``GPU`` ``CPU``
  566. Examples:
  567. >>> import mindspore.numpy as np
  568. >>> print(np.eye(2, 2))
  569. [[1. 0.]
  570. [0. 1.]]
  571. """
  572. dtype = _check_dtype(dtype)
  573. if M is None:
  574. M = N
  575. if not (isinstance(M, int) and isinstance(N, int) and isinstance(k, int)):
  576. _raise_type_error("Input tensor dimensions should be integers.")
  577. out = None
  578. if N == 0 or M == 0:
  579. # Fill the shape with any value is fine.
  580. return full((N, M), 0, dtype)
  581. out = F.eye(N, M, dtype)
  582. if k >= M or k <= -N:
  583. return full((N, M), 0, dtype)
  584. if k != 0:
  585. out = out.astype(mstype.float32)
  586. if k > 0:
  587. out_left = full((N, k), 0, dtype)
  588. out_right = out[..., 0:M-k:1]
  589. return concatenate((out_left, out_right), 1).astype(dtype)
  590. if k < 0:
  591. out_upper = full((-k, M), 0, dtype)
  592. out_lower = out[0:N+k:1, ...]
  593. return concatenate((out_upper, out_lower), 0).astype(dtype)
  594. return out
  595. def identity(n, dtype=mstype.float32):
  596. """
  597. Returns the identity tensor.
  598. Args:
  599. n (int): Number of rows and columns in the output, must be larger than 0.
  600. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype,
  601. default is :class:`mstype.float32`.
  602. Returns:
  603. A tensor of shape `(n, n)`, where all elements are equal to zero,
  604. except for the diagonal, whose values are equal to one.
  605. Supported Platforms:
  606. ``Ascend`` ``GPU`` ``CPU``
  607. Raises:
  608. TypeError: If input arguments have types not specified above.
  609. Examples:
  610. >>> import mindspore.numpy as np
  611. >>> print(np.identity(2))
  612. [[1. 0.]
  613. [0. 1.]]
  614. """
  615. if not isinstance(n, int):
  616. _raise_type_error("Input tensor dimensions should be integers.")
  617. dtype = _check_dtype(dtype)
  618. return eye(n, dtype=dtype)
  619. @constexpr
  620. def empty_compile(dtype, shape):
  621. """Returns an empty Tensor."""
  622. return Tensor_(dtype, shape)
  623. def empty(shape, dtype=mstype.float32):
  624. """
  625. Returns a new array of given shape and type, without initializing
  626. entries.
  627. Note:
  628. Numpy argument `order` is not supported.
  629. Object arrays are not supported.
  630. Args:
  631. shape (Union[int, tuple(int)]): Shape of the empty array, e.g.,
  632. (2, 3) or 2.
  633. dtype (:class:`mindspore.dtype`, optional): Desired output data-type for the
  634. array, e.g, mstype.int8. Default is mstype.float32.
  635. Returns:
  636. Tensor, array of uninitialized (arbitrary) data of the given
  637. shape and dtype.
  638. Raises:
  639. TypeError: if the input shape or dtype is invalid.
  640. Supported Platforms:
  641. ``Ascend`` ``GPU`` ``CPU``
  642. Examples:
  643. >>> import mindspore.numpy as np
  644. >>> output = np.empty((2, 3))
  645. >>> print(output)
  646. # result may vary
  647. Tensor(shape=[2, 3], dtype=Float32, value=
  648. <uninitialized>)
  649. """
  650. shape = _check_shape(shape)
  651. dtype = _check_dtype(dtype)
  652. return empty_compile(dtype, shape)
  653. def _get_shape(array_like):
  654. """Returns the shape of the array like object."""
  655. if isinstance(array_like, Tensor):
  656. return array_like.shape
  657. return asarray_const(array_like).shape
  658. def _get_dtype(array_like):
  659. """Returns the data type of the array like object."""
  660. if isinstance(array_like, Tensor):
  661. return array_like.dtype
  662. return asarray_const(array_like).dtype
  663. def _x_like(prototype, dtype, shape, constructor, fill_value=None):
  664. """
  665. Returns a tensor with the same shape and type as prototype,
  666. using constructor.
  667. """
  668. if not isinstance(prototype, ARRAY_TYPES):
  669. _raise_type_error("prototype should be int, float, bool, list, tuple, Tensor, but got", prototype)
  670. dtype_out = dtype
  671. shape_out = shape
  672. if dtype_out is None:
  673. dtype_out = _get_dtype(prototype)
  674. if shape_out is None or isinstance(shape_out, (list, tuple)) and not shape_out:
  675. shape_out = _get_shape(prototype)
  676. if fill_value is not None:
  677. return constructor(shape_out, fill_value, dtype_out)
  678. return constructor(shape_out, dtype_out)
  679. def empty_like(prototype, dtype=None, shape=None):
  680. """
  681. Returns a new array with the same shape and type as a given array.
  682. Note:
  683. Input array must have the same size across a dimension.
  684. If `prototype` is not a Tensor, dtype is float32 by default if not provided.
  685. Args:
  686. prototype (Union[Tensor, list, tuple]): The shape and data-type of `prototype`
  687. define these same attributes of the returned array.
  688. dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
  689. result.
  690. shape (int or sequence of ints, optional): Overrides the shape
  691. of the result.
  692. Returns:
  693. Tensor, array of uninitialized (arbitrary) data with the same
  694. shape and type as `prototype`.
  695. Raises:
  696. ValueError: if `prototype` is not a Tensor, list or tuple.
  697. Supported Platforms:
  698. ``Ascend`` ``GPU`` ``CPU``
  699. Examples:
  700. >>> import mindspore.numpy as np
  701. >>> a = np.ones((4,1,2))
  702. >>> output = np.empty_like(a)
  703. >>> print(output)
  704. # result may vary
  705. Tensor(shape=[4, 1, 2], dtype=Float32, value=
  706. <uninitialized>)
  707. """
  708. return _x_like(prototype, dtype, shape, empty)
  709. def ones_like(a, dtype=None, shape=None):
  710. """
  711. Returns an array of ones with the same shape and type as a given array.
  712. Note:
  713. Input array must have the same size across a dimension.
  714. If `a` is not a Tensor, dtype is float32 by default if not provided.
  715. Args:
  716. a (Union[Tensor, list, tuple]): The shape and data-type of a define these same
  717. attributes of the returned array.
  718. dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
  719. result.
  720. shape (int or sequence of ints, optional): Overrides the shape
  721. of the result.
  722. Returns:
  723. Tensor, array of ones with the same shape and type as `a`.
  724. Raises:
  725. ValueError: if `a` is not a Tensor, list or tuple.
  726. Supported Platforms:
  727. ``Ascend`` ``GPU`` ``CPU``
  728. Examples:
  729. >>> import mindspore.numpy as np
  730. >>> a = np.ones((4,1,2))
  731. >>> output = np.ones_like(a)
  732. >>> print(output)
  733. [[[1. 1.]]
  734. [[1. 1.]]
  735. [[1. 1.]]
  736. [[1. 1.]]]
  737. """
  738. return _x_like(a, dtype, shape, ones)
  739. def zeros_like(a, dtype=None, shape=None):
  740. """
  741. Returns an array of zeros with the same shape and type as a given array.
  742. Note:
  743. Input array must have the same size across a dimension.
  744. If `a` is not a Tensor, dtype is float32 by default if not provided.
  745. Args:
  746. a (Union[Tensor, list, tuple]): The shape and data-type of a define these same
  747. attributes of the returned array.
  748. dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
  749. result.
  750. shape (int or sequence of ints, optional): Overrides the shape
  751. of the result.
  752. Returns:
  753. Tensor, array of zeros with the same shape and type as `a`.
  754. Raises:
  755. ValueError: if `a` is not a Tensor, list or tuple.
  756. Supported Platforms:
  757. ``Ascend`` ``GPU`` ``CPU``
  758. Examples:
  759. >>> import mindspore.numpy as np
  760. >>> a = np.ones((4,1,2))
  761. >>> output = np.zeros_like(a)
  762. >>> print(output)
  763. [[[0. 0.]]
  764. [[0. 0.]]
  765. [[0. 0.]]
  766. [[0. 0.]]]
  767. """
  768. return _x_like(a, dtype, shape, zeros)
  769. def full_like(a, fill_value, dtype=None, shape=None):
  770. """
  771. Returns a full array with the same shape and type as a given array.
  772. Note:
  773. Input array must have the same size across a dimension.
  774. If `a` is not a Tensor, dtype is float32 by default if not provided.
  775. Args:
  776. a (Union[Tensor, list, tuple]): The shape and data-type of `a` define these same
  777. attributes of the returned array.
  778. fill_value (scalar): Fill value.
  779. dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
  780. result.
  781. shape (int or sequence of ints, optional): Overrides the shape
  782. of the result.
  783. Returns:
  784. Tensor, array of fill_value with the same shape and type as `a`.
  785. Raises:
  786. ValueError: if `a` is not a Tensor, list or tuple.
  787. Supported Platforms:
  788. ``Ascend`` ``GPU`` ``CPU``
  789. Examples:
  790. >>> import mindspore.numpy as np
  791. >>> a = np.ones((4,1,2))
  792. >>> output = np.full_like(a, 0.5)
  793. >>> print(output)
  794. [[[0.5 0.5]]
  795. [[0.5 0.5]]
  796. [[0.5 0.5]]
  797. [[0.5 0.5]]]
  798. """
  799. return _x_like(a, dtype, shape, full, fill_value=fill_value)
  800. def tri(N, M=None, k=0, dtype=mstype.float32):
  801. """
  802. Returns a tensor with ones at and below the given diagonal and zeros elsewhere.
  803. Args:
  804. N(int): Number of rows in the array.
  805. M(int, optional): Number of columns in the array. By default, `M` is taken
  806. equal to N.
  807. k(int, optional): The sub-diagonal at and below which the array is filled.
  808. :math:`k = 0` is the main diagonal, while :math:`k < 0` is below it, and :math:`k > 0` is above.
  809. The default is 0.
  810. dtype(:class:`mindspore.dtype`, optional): Data type of the returned array. The default
  811. is mstype.float32.
  812. Returns:
  813. Tensor with shape `(N, M)`, with its lower triangle filled with
  814. ones and zeros elsewhere; in other words :math:`T[i,j] = 1` for :math:`j <= i + k`,
  815. 0 otherwise.
  816. Raises:
  817. TypeError: If input arguments have types not specified above.
  818. Supported Platforms:
  819. ``Ascend`` ``GPU`` ``CPU``
  820. Examples:
  821. >>> import mindspore.numpy as np
  822. >>> output = np.tri(3, 3, 1)
  823. >>> print(output)
  824. [[1. 1. 0.]
  825. [1. 1. 1.]
  826. [1. 1. 1.]]
  827. """
  828. if M is None:
  829. M = N
  830. return nn_tril((N, M), dtype, k)
  831. def tril(m, k=0):
  832. """
  833. Returns a lower triangle of a tensor.
  834. Returns a copy of a tensor with elements above the `k-th` diagonal zeroed.
  835. Args:
  836. m (Union[Tensor, list, tuple]): The shape and data-type of `m` define these same
  837. attributes of the returned tensor.
  838. k (int, optional): Diagonal above which to zero elements. :math:`k = 0` (the default)
  839. is the main diagonal, :math:`k < 0` is below it and :math:`k > 0` is above.
  840. Returns:
  841. Lower triangle of `m`, of same shape and data-type as `m`.
  842. Supported Platforms:
  843. ``Ascend`` ``GPU`` ``CPU``
  844. Raises:
  845. TypeError: If input arguments have types not specified above.
  846. ValueError: If input `m`\'s rank :math:`< 1`.
  847. Examples:
  848. >>> import mindspore.numpy as np
  849. >>> output = np.tril(np.ones((3, 3)))
  850. >>> print(output)
  851. [[1. 0. 0.]
  852. [1. 1. 0.]
  853. [1. 1. 1.]]
  854. """
  855. if not isinstance(m, Tensor):
  856. m = asarray_const(m)
  857. dtype = m.dtype
  858. m = m.astype(mstype.float32)
  859. assist = nn_tril(m.shape, mstype.float32, k)
  860. return F.tensor_mul(assist, m).astype(dtype)
  861. def triu(m, k=0):
  862. """
  863. Returns an upper triangle of a tensor.
  864. Returns a copy of a tensor with elements below the `k-th` diagonal zeroed.
  865. Args:
  866. m (Union[Tensor, list, tuple]): The shape and data-type of `m` define these same
  867. attributes of the returned tensor.
  868. k (int, optional): Diagonal below which to zero elements. :math:`k = 0` (the default)
  869. is the main diagonal, :math:`k < 0` is below it and :math:`k > 0` is above.
  870. Returns:
  871. Upper triangle of `m`, of same shape and data-type as `m`.
  872. Raises:
  873. TypeError: If input arguments have types not specified above.
  874. ValueError: If input `m`\'s rank < 1.
  875. Supported Platforms:
  876. ``Ascend`` ``GPU`` ``CPU``
  877. Examples:
  878. >>> import mindspore.numpy as np
  879. >>> output = np.triu(np.ones((3, 3)))
  880. >>> print(output)
  881. [[1. 1. 1.]
  882. [0. 1. 1.]
  883. [0. 0. 1.]]
  884. """
  885. if not isinstance(m, Tensor):
  886. m = asarray_const(m)
  887. dtype = m.dtype
  888. m = m.astype(mstype.float32)
  889. assist = nn_triu(m.shape, mstype.float32, k)
  890. return F.tensor_mul(assist, m).astype(dtype)
  891. def diagonal(a, offset=0, axis1=0, axis2=1):
  892. """
  893. Returns specified diagonals.
  894. If `a` is 2-D, returns the diagonal of `a` with the given offset, i.e., the
  895. collection of elements of the form ``a[i, i+offset]``. If `a` has more than two
  896. dimensions, then the axes specified by `axis1` and `axis2` are used to determine
  897. the 2-D sub-array whose diagonal is returned. The shape of the resulting
  898. array can be determined by removing `axis1` and `axis2` and appending an index
  899. to the right equal to the size of the resulting diagonals.
  900. Args:
  901. a (Tensor): Array from which the diagonals are taken.
  902. offset (int, optional): Offset of the diagonal from the main diagonal.
  903. Can be positive or negative. Defaults to main diagonal.
  904. axis1 (int, optional): Axis to be used as the first axis of the 2-D
  905. sub-arrays from which the diagonals should be taken. Defaults to
  906. first axis (0).
  907. axis2 (int, optional): Axis to be used as the second axis of the 2-D
  908. sub-arrays from which the diagonals should be taken. Defaults to
  909. second axis.
  910. Returns:
  911. Tensor, if `a` is 2-D, then `a` 1-D array containing the diagonal. If
  912. ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2` are removed,
  913. and a new axis inserted at the end corresponding to the diagonal.
  914. Raises:
  915. ValueError: if the input tensor has less than two dimensions.
  916. Supported Platforms:
  917. ``Ascend`` ``GPU`` ``CPU``
  918. Examples:
  919. >>> import mindspore.numpy as np
  920. >>> a = np.arange(4).reshape(2,2).astype(np.float32)
  921. >>> print(a)
  922. [[0. 1.]
  923. [2. 3.]]
  924. >>> output = np.diagonal(a)
  925. >>> print(output)
  926. [0. 3.]
  927. >>> output = np.diagonal(a, 1)
  928. >>> print(output)
  929. [1.]
  930. >>> a = np.arange(8).reshape(2, 2, 2).astype(np.float32)
  931. >>> print(a)
  932. [[[0. 1.]
  933. [2. 3.]]
  934. [[4. 5.]
  935. [6. 7.]]]
  936. >>> output = np.diagonal(a, 0, 0, 1)
  937. >>> print(output)
  938. [[0. 6.]
  939. [1. 7.]]
  940. """
  941. return a.diagonal(offset=offset, axis1=axis1, axis2=axis2)
  942. def trace(a, offset=0, axis1=0, axis2=1, dtype=None):
  943. """
  944. Returns the sum along diagonals of the array.
  945. If `a` is 2-D, the sum along its diagonal with the given offset is returned,
  946. i.e., the sum of elements ``a[i,i+offset]`` for all `i`.
  947. If `a` has more than two dimensions, then the axes specified by `axis1` and
  948. `axis2` are used to determine the 2-D sub-arrays whose traces are returned.
  949. The shape of the resulting array is the same as that of a with `axis1` and
  950. `axis2` removed.
  951. Note:
  952. On GPU, the supported dtypes are np.float16, and np.float32.
  953. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.
  954. Args:
  955. a (Tensor): Array from which the diagonals are taken.
  956. offset (int, optional): Offset of the diagonal from the main diagonal.
  957. Can be positive or negative. Defaults to main diagonal.
  958. axis1 (int, optional): Axis to be used as the first axis of the 2-D
  959. sub-arrays from which the diagonals should be taken. Defaults to
  960. first axis (0).
  961. axis2 (int, optional): Axis to be used as the second axis of the 2-D
  962. sub-arrays from which the diagonals should be taken. Defaults to
  963. second axis.
  964. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  965. output Tensor.
  966. Returns:
  967. Tensor, sum_along_diagonals. If `a` is 2-D, the sum along the diagonal
  968. is returned. If `a` has larger dimensions, then an array of sums along
  969. diagonals is returned.
  970. Raises:
  971. ValueError: if the input tensor has less than two dimensions.
  972. Supported Platforms:
  973. ``Ascend`` ``GPU`` ``CPU``
  974. Examples:
  975. >>> import mindspore.numpy as np
  976. >>> output = np.trace(np.eye(3))
  977. >>> print(output)
  978. 3.0
  979. >>> a = np.arange(8).reshape((2,2,2))
  980. >>> output = np.trace(a)
  981. >>> print(output)
  982. [6 8]
  983. >>> a = np.arange(24).reshape((2,2,2,3))
  984. >>> output = np.trace(a).shape
  985. >>> print(output)
  986. (2, 3)
  987. """
  988. return a.trace(offset=offset, axis1=axis1, axis2=axis2, dtype=dtype)
  989. def _index(i, size, cartesian=True):
  990. """If cartesian=True, index 0 is swapped with index 1."""
  991. if cartesian:
  992. if i == 1:
  993. return 0
  994. if i == 0 and size >= 2:
  995. return 1
  996. return i
  997. def meshgrid(*xi, sparse=False, indexing='xy'):
  998. """
  999. Returns coordinate matrices from coordinate vectors.
  1000. Make `N-D` coordinate arrays for vectorized evaluations of `N-D`
  1001. scalar/vector fields over `N-D` grids, given one-dimensional
  1002. coordinate arrays `x1, x2,…, xn`.
  1003. Note:
  1004. Numpy argument copy is not supported, and a copy is always
  1005. returned.
  1006. Args:
  1007. *xi (Tensor): 1-D arrays representing the coordinates
  1008. of a grid.
  1009. indexing ('xy', 'ij', optional): Cartesian ('xy', default) or
  1010. matrix ('ij') indexing of output. In the 2-D case with
  1011. inputs of length `M` and `N`, the outputs are of shape `(N, M)`
  1012. for 'xy' indexing and `(M, N)` for 'ij' indexing. In the 3-D
  1013. case with inputs of length `M`, `N` and `P`, outputs are of shape
  1014. `(N, M, P)` for 'xy' indexing and `(M, N, P)` for 'ij' indexing.
  1015. sparse (bool, optional): If True a sparse grid is returned in
  1016. order to conserve memory. Default is False.
  1017. Returns:
  1018. Tuple of tensors, for vectors `x1, x2,…, xn` with lengths
  1019. ``Ni=len(xi)``, return `(N1, N2, N3,...Nn)` shaped arrays if
  1020. ``indexing='ij'`` or `(N2, N1, N3,...Nn)` shaped arrays if
  1021. ``indexing='xy'`` with the elements of `xi` repeated to fill the matrix
  1022. along the first dimension for `x1`, the second for `x2` and so on.
  1023. Raises:
  1024. TypeError: if the input is not a tensor, or sparse is not boolean, or
  1025. indexing is not 'xy' or 'ij'.
  1026. Supported Platforms:
  1027. ``Ascend`` ``GPU`` ``CPU``
  1028. Examples:
  1029. >>> import mindspore.numpy as np
  1030. >>> x = np.linspace(0, 1, 3)
  1031. >>> y = np.linspace(0, 1, 2)
  1032. >>> xv, yv = np.meshgrid(x, y)
  1033. >>> print(xv)
  1034. [[0. 0.5 1. ]
  1035. [0. 0.5 1. ]]
  1036. >>> print(yv)
  1037. [[0. 0. 0.]
  1038. [1. 1. 1.]]
  1039. >>> xv, yv = np.meshgrid(x, y, sparse=True)
  1040. >>> print(xv)
  1041. [[0. 0.5 1. ]]
  1042. >>> print(yv)
  1043. [[0.]
  1044. [1.]]
  1045. """
  1046. _check_input_tensor(*xi)
  1047. if not isinstance(sparse, bool):
  1048. _raise_type_error('argument sparse should be boolean')
  1049. if indexing not in ('xy', 'ij'):
  1050. _raise_type_error("Valid values for `indexing` are 'xy' and 'ij'.")
  1051. shape_out = ()
  1052. for x in xi:
  1053. shape_out += (x.size,)
  1054. if _is_shape_empty(shape_out):
  1055. return ones(shape_out)
  1056. grids = []
  1057. for x in xi:
  1058. if F.rank(x) == 1:
  1059. grids.append(x)
  1060. else:
  1061. grids.append(ravel(x))
  1062. ndim = len(grids)
  1063. cartesian = indexing == 'xy'
  1064. shape_out = ()
  1065. for i in range(len(grids)):
  1066. grid_index = _index(i, ndim, cartesian=cartesian)
  1067. shape_out += (F.shape(grids[grid_index])[0],)
  1068. res = []
  1069. for i, x in enumerate(grids):
  1070. grid_index = _index(i, ndim, cartesian=cartesian)
  1071. shape_expanded = _expanded_shape(ndim, shape_out[grid_index], grid_index)
  1072. x = x.reshape(shape_expanded)
  1073. if not sparse:
  1074. x = F.tile(x, _tile_size(shape_expanded, shape_out, ndim))
  1075. res.append(x)
  1076. return res
  1077. class NdGrid:
  1078. """
  1079. Construct a multi-dimensional "meshgrid".
  1080. ``grid = NdGrid()`` creates an instance which will return a mesh-grid
  1081. when indexed.
  1082. If instantiated with an argument of ``sparse=True``, the mesh-grid is
  1083. open (or not fleshed out) so that only one-dimension of each
  1084. returned argument is greater than 1.
  1085. Args:
  1086. sparse (bool): Whether the grid is sparse or not. Default is
  1087. False.
  1088. Returns:
  1089. Tensor or tuple of tensor, a meshgrid. If ``sparse=False``, returns
  1090. tensors are all of the same dimensions; and if ``sparse=True``,
  1091. returns tensors with only one dimension not equal to `1`.
  1092. """
  1093. def __init__(self, sparse=False):
  1094. self.sparse = sparse
  1095. def __getitem__(self, keys):
  1096. if isinstance(keys, slice):
  1097. keys = (keys,)
  1098. xi = []
  1099. for k in keys:
  1100. if not isinstance(k.start, int) or not isinstance(k.stop, int):
  1101. _raise_type_error('slice indices must be integers')
  1102. if k.step:
  1103. step = k.step
  1104. else:
  1105. step = 1
  1106. if isinstance(step, complex):
  1107. v = linspace(k.start, k.stop, int(abs(step)))
  1108. else:
  1109. v = arange(k.start, k.stop, step)
  1110. xi.append(v)
  1111. grids = meshgrid(*xi, sparse=self.sparse, indexing='ij')
  1112. if len(grids) == 1:
  1113. return grids[0]
  1114. if self.sparse:
  1115. return grids
  1116. if isinstance(grids, Tensor_):
  1117. return grids
  1118. expanded = []
  1119. for grid in grids:
  1120. expanded.append(F.expand_dims(grid, 0))
  1121. res = concatenate(tuple(expanded))
  1122. return res
  1123. class MGridClass(NdGrid):
  1124. """
  1125. mgrid is an :class:`NdGrid` instance with ``sparse=False``.
  1126. The dimension and number of the output arrays are equal to the number
  1127. of indexing dimensions. If the step length is not a complex number,
  1128. then the stop is not inclusive. However, if the step length is a complex
  1129. number (e.g. 5j), then the integer part of its magnitude is interpreted
  1130. as specifying the number of points to create between the start and
  1131. stop values, where the stop value is inclusive.
  1132. Note:
  1133. Not supported in graph mode.
  1134. Unlike Numpy, if the step length is a complex number with a real
  1135. component, the step length is handled as equivalent to
  1136. ``int(abs(step))``.
  1137. Returns:
  1138. Tensor or tuple of tensor, a meshgrid.
  1139. Raises:
  1140. TypeError: if slicing indices are not integers.
  1141. Supported Platforms:
  1142. ``Ascend`` ``GPU`` ``CPU``
  1143. Examples:
  1144. >>> from mindspore.numpy import mgrid
  1145. >>> output = mgrid[0:5, 0:5]
  1146. >>> print(output)
  1147. [[[0 0 0 0 0]
  1148. [1 1 1 1 1]
  1149. [2 2 2 2 2]
  1150. [3 3 3 3 3]
  1151. [4 4 4 4 4]]
  1152. [[0 1 2 3 4]
  1153. [0 1 2 3 4]
  1154. [0 1 2 3 4]
  1155. [0 1 2 3 4]
  1156. [0 1 2 3 4]]]
  1157. >>> output = mgrid[-1:1:5j]
  1158. >>> print(output)
  1159. [-1. -0.5 0. 0.5 1. ]
  1160. """
  1161. def __init__(self):
  1162. super(MGridClass, self).__init__(sparse=False)
  1163. class OGridClass(NdGrid):
  1164. """
  1165. ogrid is an :class:`NdGrid` instance with ``sparse=True``.
  1166. The dimension and number of the output arrays are equal to the number
  1167. of indexing dimensions. If the step length is not a complex number,
  1168. then the stop is not inclusive. However, if the step length is a complex
  1169. number (e.g. 5j), then the integer part of its magnitude is interpreted
  1170. as specifying the number of points to create between the start and
  1171. stop values, where the stop value is inclusive.
  1172. Note:
  1173. Not supported in graph mode.
  1174. Unlike Numpy, if the step length is a complex number with a real
  1175. component, the step length is handled as equivalent to
  1176. ``int(abs(step))``.
  1177. Raises:
  1178. TypeError: if slicing indices are not integers.
  1179. Supported Platforms:
  1180. ``Ascend`` ``GPU`` ``CPU``
  1181. Examples:
  1182. >>> from mindspore.numpy import ogrid
  1183. >>> output = ogrid[0:5,0:5]
  1184. >>> print(output)
  1185. [Tensor(shape=[5, 1], dtype=Int32, value=
  1186. [[0],
  1187. [1],
  1188. [2]
  1189. [3],
  1190. [4]]), Tensor(shape=[1, 5], dtype=Int32, value=
  1191. [[0, 1, 2, 3, 4]])]
  1192. >>> output = ogrid[-1:1:5j]
  1193. >>> print(output)
  1194. [-1. -0.5 0. 0.5 1. ]
  1195. """
  1196. def __init__(self):
  1197. super(OGridClass, self).__init__(sparse=True)
  1198. mgrid = MGridClass()
  1199. ogrid = OGridClass()
  1200. def diag(v, k=0):
  1201. """
  1202. Extracts a diagonal or construct a diagonal array.
  1203. Args:
  1204. v (Tensor): If `v` is a 2-D array, return a copy of its `k-th` diagonal.
  1205. If `v` is a 1-D array, return a 2-D array with v on the `k-th` diagonal.
  1206. k (int, optional): Diagonal in question. The default is 0. Use ``k>0`` for
  1207. diagonals above the main diagonal, and ``k<0`` for diagonals below the
  1208. main diagonal.
  1209. Returns:
  1210. Tensor, the extracted diagonal or constructed diagonal array.
  1211. Raises:
  1212. ValueError: if input is not 1-D or 2-D.
  1213. Supported Platforms:
  1214. ``Ascend`` ``GPU`` ``CPU``
  1215. Examples:
  1216. >>> import mindspore.numpy as np
  1217. >>> x = np.arange(9).reshape((3,3))
  1218. >>> print(x)
  1219. [[0 1 2]
  1220. [3 4 5]
  1221. [6 7 8]]
  1222. >>> output = np.diag(x)
  1223. >>> print(output)
  1224. [0 4 8]
  1225. >>> output = np.diag(x, k=1)
  1226. >>> print(output)
  1227. [1 5]
  1228. >>> output = np.diag(x, k=-1)
  1229. >>> print(output)
  1230. [3 7]
  1231. """
  1232. ndim = F.rank(v)
  1233. if ndim == 1:
  1234. return diagflat(v, k=k)
  1235. if ndim == 2:
  1236. shape = F.shape(v)
  1237. dtype = F.dtype(v)
  1238. if _is_shape_empty(shape):
  1239. return _empty(dtype, (0,))
  1240. e = eye(shape[0], shape[1], k, dtype)
  1241. prod = F.tensor_mul(v, e)
  1242. cast_type = dtype
  1243. if not _check_is_float(dtype):
  1244. # reduce sum only supports float types
  1245. cast_type = mstype.float32
  1246. prod = F.cast(prod, cast_type)
  1247. res = F.reduce_sum(prod, 1)
  1248. res = res[_max(0, -k): _min(shape[0], _max(0, shape[1] - k))]
  1249. if not _check_same_type(cast_type, dtype):
  1250. res = F.cast(res, dtype)
  1251. return res
  1252. return _raise_value_error("Input must be 1- or 2-d.")
  1253. def diagflat(v, k=0):
  1254. """
  1255. Creates a two-dimensional array with the flattened input as a diagonal.
  1256. Note:
  1257. On GPU, the supported dtypes are np.float16, and np.float32.
  1258. Args:
  1259. v (Tensor): Input data, which is flattened and set as the `k-th` diagonal
  1260. of the output.
  1261. k (int, optional): Diagonal to set; 0, the default, corresponds to the
  1262. "main" diagonal, a positive (negative) `k` giving the number of the
  1263. diagonal above (below) the main.
  1264. Returns:
  1265. Tensor, The 2-D output array.
  1266. Raises:
  1267. TypeError: if the input is not a tensor.
  1268. Supported Platforms:
  1269. ``Ascend`` ``GPU`` ``CPU``
  1270. Examples:
  1271. >>> import mindspore.numpy as np
  1272. >>> output = np.diagflat(np.asarray([[1,2], [3,4]]))
  1273. >>> print(output)
  1274. [[1 0 0 0]
  1275. [0 2 0 0]
  1276. [0 0 3 0]
  1277. [0 0 0 4]]
  1278. >>> output = np.diagflat(np.asarray([1,2]), 1)
  1279. >>> print(output)
  1280. [[0 1 0]
  1281. [0 0 2]
  1282. [0 0 0]]
  1283. """
  1284. _check_input_tensor(v)
  1285. dtype = F.dtype(v)
  1286. k_abs = _abs(k)
  1287. if _is_shape_empty(F.shape(v)):
  1288. return zeros((k_abs, k_abs), dtype)
  1289. v = ravel(v)
  1290. size = F.shape(v)[0]
  1291. e = eye(size, size, 0, dtype)
  1292. res = F.tensor_mul(v, e)
  1293. if k != 0:
  1294. pad_y = zeros((size, k_abs), dtype)
  1295. pad_x = zeros((k_abs, size + k_abs), dtype)
  1296. if k < 0:
  1297. res = concatenate((res, pad_y), axis=1)
  1298. res = concatenate((pad_x, res), axis=0)
  1299. else:
  1300. res = concatenate((pad_y, res), axis=1)
  1301. res = concatenate((res, pad_x), axis=0)
  1302. return res
  1303. def diag_indices(n, ndim=2):
  1304. """
  1305. Returns the indices to access the main diagonal of an array.
  1306. This returns a tuple of indices that can be used to access the main
  1307. diagonal of an array a with ``a.ndim >= 2`` dimensions and shape `(n, n, …, n)`.
  1308. For ``a.ndim = 2`` this is the usual diagonal, for ``a.ndim > 2`` this is the set
  1309. of indices to access ``a[i, i, ..., i]`` for ``i = [0..n-1]``.
  1310. Args:
  1311. n (int): The size, along each dimension, of the arrays for which
  1312. the returned indices can be used.
  1313. ndim (int, optional): The number of dimensions.
  1314. Returns:
  1315. Tuple of Tensor.
  1316. Raises:
  1317. TypeError: if input are not integers.
  1318. Supported Platforms:
  1319. ``Ascend`` ``GPU`` ``CPU``
  1320. Examples:
  1321. >>> import mindspore.numpy as np
  1322. >>> output = np.diag_indices(5, 3)
  1323. >>> print(output)
  1324. (Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]),
  1325. Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]),
  1326. Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]))
  1327. """
  1328. if not isinstance(n, int) or not isinstance(ndim, int):
  1329. _raise_type_error('input must be integers')
  1330. return _list_comprehensions(ndim, arange(start=0, stop=n), True)
  1331. def ix_(*args):
  1332. r"""
  1333. Constructs an open mesh from multiple sequences.
  1334. This function takes `N` 1-D sequences and returns `N` outputs with `N`
  1335. dimensions each, such that the shape is 1 in all but one dimension
  1336. and the dimension with the non-unit shape value cycles through all
  1337. N dimensions.
  1338. Using ix\_ one can quickly construct index arrays that will index
  1339. the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array
  1340. ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.
  1341. Note:
  1342. Boolean masks are not supported.
  1343. Args:
  1344. *args (Tensor): 1-D sequences.
  1345. Returns:
  1346. Tuple of Tensor, `N` arrays with `N` dimensions each, with `N` the
  1347. number of input sequences. Together these arrays form an open
  1348. mesh.
  1349. Raises:
  1350. TypeError: if the input is not a tensor.
  1351. Supported Platforms:
  1352. ``Ascend`` ``GPU`` ``CPU``
  1353. Examples:
  1354. >>> import mindspore.numpy as np
  1355. >>> ixgrid = np.ix_(np.array([0, 1]), np.array([2, 4]))
  1356. >>> print(ixgrid)
  1357. (Tensor(shape=[2, 1], dtype=Int32, value=
  1358. [[0],
  1359. [1]]), Tensor(shape=[1, 2], dtype=Int32, value=
  1360. [[2, 4]]))
  1361. """
  1362. _check_input_tensor(*args)
  1363. ndim = len(args)
  1364. res = ()
  1365. for i, arr in enumerate(args):
  1366. if F.rank(arr) != 1:
  1367. return _raise_value_error('Cross index must be 1 dimensional')
  1368. res += (F.reshape(arr, _expanded_shape(ndim, arr.size, i)),)
  1369. return res
  1370. def vander(x, N=None, increasing=False):
  1371. """
  1372. Generates a Vandermonde matrix.
  1373. The columns of the output matrix are powers of the input vector. The order of
  1374. the powers is determined by the increasing boolean argument. Specifically, when
  1375. increasing is `False`, the i-th output column is the input vector raised element-wise
  1376. to the power of :math:`N - i - 1`. Such a matrix with a geometric progression in each row
  1377. is named for Alexandre-Theophile Vandermonde.
  1378. Args:
  1379. x (Union[list, tuple, Tensor]): 1-D input array.
  1380. N (int, optional): Number of columns in the output. If N is not specified, a
  1381. square array is returned (``N = len(x)``).
  1382. increasing (bool, optional): Order of the powers of the columns. If True, the
  1383. powers increase from left to right, if False (the default) they are reversed.
  1384. Returns:
  1385. Vandermonde matrix. If `increasing` is `False`, the first column is :math:`x^{(N-1)}`,
  1386. the second :math:`x^{(N-2)}` and so forth. If `increasing` is `True`, the columns are
  1387. :math:`x^0, x^1, ..., x^{(N-1)}`.
  1388. Raises:
  1389. TypeError: If inputs have types not specified above.
  1390. ValueError: If `x` is not 1-D, or `N` < 0.
  1391. Supported Platforms:
  1392. ``Ascend`` ``GPU`` ``CPU``
  1393. Examples:
  1394. >>> import mindspore.numpy as np
  1395. >>> print(np.vander([1., 2., 3., 4., 5.]))
  1396. [[ 1. 1. 1. 1. 1.]
  1397. [ 16. 8. 4. 2. 1.]
  1398. [ 81. 27. 9. 3. 1.]
  1399. [256. 64. 16. 4. 1.]
  1400. [625. 125. 25. 5. 1.]]
  1401. """
  1402. if isinstance(x, (list, tuple)):
  1403. x = asarray_const(x)
  1404. elif not isinstance(x, Tensor):
  1405. _raise_type_error("Input x must be list, tuple or Tensor, but got ", x)
  1406. if x.ndim != 1:
  1407. _raise_value_error("Input x must be 1-D, but got dimension=", x.ndim)
  1408. N = N or x.size
  1409. if not isinstance(N, int):
  1410. _raise_type_error("Input N must be an integer.")
  1411. if N <= 0:
  1412. _raise_value_error("Input N must > 0.")
  1413. if not isinstance(increasing, bool):
  1414. _raise_type_error("increasing must be a bool.")
  1415. exponent = _iota(x.dtype, N, increasing)
  1416. x = F.expand_dims(x, 1)
  1417. exponent = F.expand_dims(exponent, 0)
  1418. return F.tensor_pow(x, exponent)
  1419. def indices(dimensions, dtype=mstype.int32, sparse=False):
  1420. """
  1421. Returns an array representing the indices of a grid.
  1422. Computes an array where the subarrays contain index values 0, 1, …
  1423. varying only along the corresponding axis.
  1424. Args:
  1425. dimensions (tuple or list of ints): The shape of the grid.
  1426. dtype (:class:`mindspore.dtype`, optional): Data type of the result.
  1427. sparse (boolean, optional): Defaults to False. Return a sparse
  1428. representation of the grid instead of a dense representation.
  1429. Returns:
  1430. Tensor or tuple of Tensor, If `sparse` is False, returns one array
  1431. of grid indices, ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
  1432. If sparse is True, returns a tuple of arrays, with
  1433. ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
  1434. ``dimensions[i]`` in the `ith` place
  1435. Raises:
  1436. TypeError: if input dimensions is not a tuple or list.
  1437. Supported Platforms:
  1438. ``Ascend`` ``GPU`` ``CPU``
  1439. Examples:
  1440. >>> import mindspore.numpy as np
  1441. >>> grid = np.indices((2, 3))
  1442. >>> print(grid)
  1443. [Tensor(shape=[2, 3], dtype=Int32, value=
  1444. [[0, 0, 0],
  1445. [1, 1, 1]]), Tensor(shape=[2, 3], dtype=Int32, value=
  1446. [[0, 1, 2],
  1447. [0, 1, 2]])]
  1448. """
  1449. if not isinstance(dimensions, (tuple, list)):
  1450. _raise_type_error('Shape of the grid must be tuple or list')
  1451. grids = ()
  1452. for d in dimensions:
  1453. grids += (arange(d, dtype=dtype),)
  1454. return meshgrid(*grids, sparse=sparse, indexing='ij')
  1455. def _check_window_size(x):
  1456. """Returns True if window size is greater than 1."""
  1457. if not isinstance(x, int):
  1458. _raise_type_error('the number fo points should be an int')
  1459. return x > 1
  1460. def bartlett(M):
  1461. """
  1462. Returns the Bartlett window.
  1463. The Bartlett window is very similar to a triangular window, except that the
  1464. end points are at zero. It is often used in signal processing for tapering a
  1465. signal, without generating too much ripple in the frequency domain.
  1466. Args:
  1467. M (int): Number of points in the output window. If zero or less, an empty
  1468. array is returned.
  1469. Returns:
  1470. Tensor, the triangular window, with the maximum value normalized to one
  1471. (the value one appears only if the number of samples is odd), with the
  1472. first and last samples equal to zero.
  1473. Raises:
  1474. TypeError: if `M` is not an int.
  1475. Supported Platforms:
  1476. ``Ascend`` ``GPU`` ``CPU``
  1477. Examples:
  1478. >>> import mindspore.numpy as np
  1479. >>> print(np.bartlett(12))
  1480. [0. 0.18181819 0.36363637 0.5454545 0.72727275 0.9090909
  1481. 0.9090909 0.72727275 0.5454545 0.36363637 0.18181819 0. ]
  1482. """
  1483. if not _check_window_size(M):
  1484. return ones(_max(0, M))
  1485. n = _iota(mstype.float32, M)
  1486. m_minus_one = _to_tensor(M - 1)
  1487. return _to_tensor(1) - F.absolute(_to_tensor(2)*n - m_minus_one)/m_minus_one
  1488. def blackman(M):
  1489. """
  1490. Returns the Blackman window.
  1491. The Blackman window is a taper formed by using the first three terms of a
  1492. summation of cosines. It was designed to have close to the minimal leakage
  1493. possible. It is close to optimal, only slightly worse than a Kaiser window.
  1494. Args:
  1495. M (int): Number of points in the output window. If zero or less, an empty
  1496. array is returned.
  1497. Returns:
  1498. Tensor, the window, with the maximum value normalized to one (the value
  1499. one appears only if the number of samples is odd).
  1500. Raises:
  1501. TypeError: if `M` is not an int.
  1502. Supported Platforms:
  1503. ``Ascend`` ``GPU`` ``CPU``
  1504. Examples:
  1505. >>> import mindspore.numpy as np
  1506. >>> print(np.blackman(12))
  1507. [-1.4901161e-08 3.2606430e-02 1.5990365e-01 4.1439798e-01
  1508. 7.3604518e-01 9.6704674e-01 9.6704674e-01 7.3604518e-01
  1509. 4.1439798e-01 1.5990365e-01 3.2606430e-02 -1.4901161e-08]
  1510. """
  1511. if not _check_window_size(M):
  1512. return ones(_max(0, M))
  1513. n_doubled = arange(1 - M, M, 2, dtype=mstype.float32)
  1514. return (_to_tensor(0.42) + _to_tensor(0.5)*F.cos(_to_tensor(pi/(M - 1))*n_doubled) +
  1515. _to_tensor(0.08)*F.cos(_to_tensor(2*pi/(M - 1))*n_doubled))
  1516. def hamming(M):
  1517. """
  1518. Returns the Hamming window.
  1519. The Hamming window is a taper formed by using a weighted cosine.
  1520. Args:
  1521. M (int): Number of points in the output window. If zero or less, an empty
  1522. array is returned.
  1523. Returns:
  1524. Tensor, the window, with the maximum value normalized to one (the value
  1525. one appears only if the number of samples is odd).
  1526. Raises:
  1527. TypeError: if `M` is not an int.
  1528. Supported Platforms:
  1529. ``Ascend`` ``GPU`` ``CPU``
  1530. Examples:
  1531. >>> import mindspore.numpy as np
  1532. >>> print(np.hamming(12))
  1533. [0.08000001 0.15302339 0.34890914 0.6054648 0.841236 0.9813669
  1534. 0.9813668 0.8412359 0.6054647 0.34890908 0.15302327 0.08000001]
  1535. """
  1536. if not _check_window_size(M):
  1537. return ones(_max(0, M))
  1538. n = _iota(mstype.float32, M)
  1539. return _to_tensor(0.54) - _to_tensor(0.46)*F.cos(_to_tensor(2*pi/(M - 1))*n)
  1540. def hanning(M):
  1541. """
  1542. Returns the Hanning window.
  1543. The Hanning window is a taper formed by using a weighted cosine.
  1544. Args:
  1545. M (int): Number of points in the output window. If zero or less, an empty
  1546. array is returned.
  1547. Returns:
  1548. Tensor, the window, with the maximum value normalized to one (the value
  1549. one appears only if the number of samples is odd).
  1550. Raises:
  1551. TypeError: if `M` is not an int.
  1552. Supported Platforms:
  1553. ``Ascend`` ``GPU`` ``CPU``
  1554. Examples:
  1555. >>> import mindspore.numpy as np
  1556. >>> print(np.hanning(12))
  1557. [0. 0.07937324 0.29229254 0.5711574 0.8274304 0.9797465
  1558. 0.97974646 0.82743025 0.5711573 0.29229245 0.07937312 0. ]
  1559. """
  1560. if not _check_window_size(M):
  1561. return ones(_max(0, M))
  1562. n = _iota(mstype.float32, M)
  1563. return _to_tensor(0.5) - _to_tensor(0.5)*F.cos(_to_tensor(2*pi/(M - 1))*n)
  1564. @constexpr
  1565. def tri_indices(n, k=0, m=None, upper=True):
  1566. """Returns triu/tril indices in o(nm) time."""
  1567. if not isinstance(n, (int, float, bool)):
  1568. raise TypeError("Input n must be a number.")
  1569. if not isinstance(k, (int, float, bool)):
  1570. raise TypeError("Input k must be a number.")
  1571. if m is None:
  1572. m = n
  1573. elif not isinstance(m, (int, float, bool)):
  1574. raise TypeError("Input m must be a number.")
  1575. if upper:
  1576. compare = operator.ge
  1577. else:
  1578. compare = operator.le
  1579. x_coordinate = []
  1580. y_coordinate = []
  1581. # math.ceil is used to match numpy's behaviour
  1582. for i in range(math.ceil(n)):
  1583. curr_limit = i + k
  1584. for j in range(math.ceil(m)):
  1585. if compare(j, curr_limit):
  1586. x_coordinate.append(i)
  1587. y_coordinate.append(j)
  1588. return asarray_const(x_coordinate), asarray_const(y_coordinate)
  1589. def triu_indices(n, k=0, m=None):
  1590. """
  1591. Returns the indices for the upper-triangle of an (n, m) array.
  1592. Args:
  1593. n (int): The size of the arrays for which the returned indices will be valid.
  1594. k (int, optional): Diagonal offset, default is 0.
  1595. m (int, optional): The column dimension of the arrays for which the returned
  1596. arrays will be valid. By default `m` is taken equal to `n`.
  1597. Returns:
  1598. The indices for the triangle. The returned tuple contains two tensors, each
  1599. with the indices along one dimension of the tensor.
  1600. Raises:
  1601. TypeError: if `n`, `k`, `m` are not numbers.
  1602. Supported Platforms:
  1603. ``Ascend`` ``GPU`` ``CPU``
  1604. Examples:
  1605. >>> import mindspore.numpy as np
  1606. >>> print(np.triu_indices(3))
  1607. (Tensor(shape=[6], dtype=Int32, value= [0, 0, 0, 1, 1, 2]),
  1608. Tensor(shape=[6], dtype=Int32, value= [0, 1, 2, 1, 2, 2]))
  1609. """
  1610. return tri_indices(n, k, m, True)
  1611. def tril_indices(n, k=0, m=None):
  1612. """
  1613. Returns the indices for the lower-triangle of an (n, m) array.
  1614. Args:
  1615. n (int): The size of the arrays for which the returned indices will be valid.
  1616. k (int, optional): Diagonal offset, default is 0.
  1617. m (int, optional): The column dimension of the arrays for which the returned
  1618. arrays will be valid. By default `m` is taken equal to `n`.
  1619. Returns:
  1620. The indices for the triangle. The returned tuple contains two tensors, each
  1621. with the indices along one dimension of the tensor.
  1622. Raises:
  1623. TypeError: if `n`, `k`, `m` are not numbers.
  1624. Supported Platforms:
  1625. ``Ascend`` ``GPU`` ``CPU``
  1626. Examples:
  1627. >>> import mindspore.numpy as np
  1628. >>> print(np.tril_indices(3))
  1629. (Tensor(shape=[6], dtype=Int32, value= [0, 1, 1, 2, 2, 2]),
  1630. Tensor(shape=[6], dtype=Int32, value= [0, 0, 1, 0, 1, 2]))
  1631. """
  1632. return tri_indices(n, k, m, False)
  1633. def triu_indices_from(arr, k=0):
  1634. """
  1635. Returns the indices for the upper-triangle of `arr`.
  1636. Args:
  1637. arr (Union[Tensor, list, tuple]): 2-dimensional array.
  1638. k (int, optional): Diagonal offset, default is 0.
  1639. Returns:
  1640. triu_indices_from, tuple of 2 tensor, shape(N)
  1641. Indices for the upper-triangle of `arr`.
  1642. Raises:
  1643. TypeError: if `arr` cannot be converted to tensor, or `k` is not a number.
  1644. ValueError: if `arr` cannot be converted to a 2-dimensional tensor.
  1645. Supported Platforms:
  1646. ``Ascend`` ``GPU`` ``CPU``
  1647. Examples:
  1648. >>> import mindspore.numpy as np
  1649. >>> tensor = np.ones((3,3))
  1650. >>> print(np.triu_indices_from(tensor))
  1651. (Tensor(shape=[6], dtype=Int32, value= [0, 0, 0, 1, 1, 2]),
  1652. Tensor(shape=[6], dtype=Int32, value= [0, 1, 2, 1, 2, 2]))
  1653. """
  1654. arr = asarray(arr)
  1655. if arr.ndim != 2:
  1656. _raise_value_error("input array must be 2-d")
  1657. return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1])
  1658. def tril_indices_from(arr, k=0):
  1659. """
  1660. Returns the indices for the lower-triangle of `arr`.
  1661. Args:
  1662. arr (Union[Tensor, list, tuple]): 2-dimensional array.
  1663. k (int, optional): Diagonal offset, default is 0.
  1664. Returns:
  1665. triu_indices_from, tuple of 2 tensor, shape(N)
  1666. Indices for the upper-triangle of `arr`.
  1667. Raises:
  1668. TypeError: if `arr` cannot be converted to tensor, or `k` is not a number.
  1669. ValueError: if `arr` cannot be converted to a 2-dimensional tensor.
  1670. Supported Platforms:
  1671. ``Ascend`` ``GPU`` ``CPU``
  1672. Examples:
  1673. >>> import mindspore.numpy as np
  1674. >>> tensor = np.ones((3,3))
  1675. >>> print(np.tril_indices_from(tensor))
  1676. (Tensor(shape=[6], dtype=Int32, value= [0, 1, 1, 2, 2, 2]),
  1677. Tensor(shape=[6], dtype=Int32, value= [0, 0, 1, 0, 1, 2]))
  1678. """
  1679. arr = asarray(arr)
  1680. if arr.ndim != 2:
  1681. _raise_value_error("input array must be 2-d")
  1682. return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1])
  1683. def histogram_bin_edges(a, bins=10, range=None, weights=None): # pylint: disable=redefined-builtin
  1684. """
  1685. Function to calculate only the edges of the bins used by the histogram function.
  1686. Note:
  1687. String values for `bins` is not supported.
  1688. Args:
  1689. a (Union[int, float, bool, list, tuple, Tensor]): Input data. The histogram
  1690. is computed over the flattened array.
  1691. bins ((Union[int, tuple, list, Tensor])): If `bins` is an int, it defines the number
  1692. of equal-width bins in the given range (10, by default). If `bins` is a
  1693. sequence, it defines the bin edges, including the rightmost edge,
  1694. allowing for non-uniform bin widths.
  1695. range((float, float), optional): The lower and upper range of the bins. If
  1696. not provided, `range` is simply ``(a.min(), a.max())``. Values outside
  1697. the range are ignored. The first element of the range must be less than
  1698. or equal to the second. Default is None.
  1699. weights(Union[int, float, bool, list, tuple, Tensor], optional): An array of weights,
  1700. of the same shape as `a`. Each value in `a` only contributes its associated weight
  1701. towards the bin count (instead of 1). This is currently not used by any of the bin
  1702. estimators, but may be in the future. Default is None.
  1703. Returns:
  1704. Tensor, the edges to pass into `histogram`.
  1705. Supported Platforms:
  1706. ``Ascend`` ``GPU`` ``CPU``
  1707. Raises:
  1708. TypeError: if `bins` is an array and not one-dimensional.
  1709. Examples:
  1710. >>> import mindspore.numpy as np
  1711. >>> arr = np.array([0, 0, 0, 1, 2, 3, 3, 4, 5])
  1712. >>> print(np.histogram_bin_edges(arr, bins=2))
  1713. [0. 2.5 5. ]
  1714. """
  1715. a = _to_tensor(a)
  1716. if weights is not None:
  1717. weights = _to_tensor(weights)
  1718. if F.shape(a) != F.shape(weights):
  1719. _raise_value_error('weights should have the same shape as a')
  1720. if isinstance(bins, (tuple, list, Tensor)):
  1721. bins = _to_tensor(bins)
  1722. if F.rank(bins) != 1:
  1723. _raise_value_error('`bins` must be 1d, when an array')
  1724. return bins
  1725. if isinstance(bins, str):
  1726. # linspace does not support Tensor for num
  1727. _raise_unimplemented_error('string value for `bins` not implemented')
  1728. a = a.ravel().astype(mstype.float32)
  1729. if range is None:
  1730. start = F.reduce_min(a)
  1731. end = F.reduce_max(a)
  1732. else:
  1733. if not isinstance(range, (list, tuple)) or len(range) != 2:
  1734. _raise_value_error('`range` should take the form (start, end)')
  1735. start, end = range
  1736. if start > end:
  1737. _raise_value_error('max must be larger than min in range parameter')
  1738. start, end = _to_tensor(start, end)
  1739. no_range = (end - start) == 0
  1740. start = where(no_range, start - 0.5, start)
  1741. end = where(no_range, end + 0.5, end)
  1742. return linspace(start, end, bins + 1)
  1743. def _pad_empty(arr, pad_width):
  1744. """
  1745. pads the array with constant values, used in mode: "empty"
  1746. """
  1747. dtype = arr.dtype
  1748. for i in range(arr.ndim):
  1749. shape = arr.shape
  1750. pad_before = ()
  1751. pad_after = ()
  1752. # To avoid any memory issues, we don't make tensor with 0s in their shapes
  1753. if pad_width[i][0] > 0:
  1754. pad_before += (empty(_tuple_setitem(shape, i, pad_width[i][0]), dtype=dtype),)
  1755. if pad_width[i][1] > 0:
  1756. pad_after += (empty(_tuple_setitem(shape, i, pad_width[i][1]), dtype=dtype),)
  1757. tensor_with_pad = pad_before + (arr,) + pad_after
  1758. arr = concatenate(tensor_with_pad, axis=i)
  1759. return arr
  1760. def _pad_constant(arr, pad_width, value):
  1761. """
  1762. pads the array with constant values, used in mode: "constant"
  1763. """
  1764. dtype = arr.dtype
  1765. for i in range(arr.ndim):
  1766. shape = arr.shape
  1767. pad_before = ()
  1768. pad_after = ()
  1769. # To avoid any memory issues, we don't make tensor with 0s in their shapes
  1770. if pad_width[i][0] > 0:
  1771. pad_before += (full(_tuple_setitem(shape, i, pad_width[i][0]), value[i][0], dtype=dtype),)
  1772. if pad_width[i][1] > 0:
  1773. pad_after += (full(_tuple_setitem(shape, i, pad_width[i][1]), value[i][1], dtype=dtype),)
  1774. tensor_with_pad = pad_before + (arr,) + pad_after
  1775. arr = concatenate(tensor_with_pad, axis=i)
  1776. return arr
  1777. def _pad_statistic(arr, pad_width, stat_length, stat_op):
  1778. """
  1779. pads the array with values calculated along the given axis, used in mode: "maximum",
  1780. "minimum", "mean"
  1781. """
  1782. ndim = arr.ndim
  1783. shape = arr.shape
  1784. if stat_length is None:
  1785. stat_length = _make_stat_length(shape)
  1786. else:
  1787. stat_length = _convert_pad_to_nd(stat_length, ndim)
  1788. stat_length = _limit_stat_length(stat_length, shape)
  1789. for i in range(ndim):
  1790. pad_before = stat_op(_slice_along_axis(arr, i, 0, stat_length[i][0]), i)
  1791. pad_before = (F.tile(pad_before, _tuple_setitem((1,)*ndim, i, pad_width[i][0])),)
  1792. pad_after = stat_op(_slice_along_axis(arr, i, shape[i]-stat_length[i][1], shape[i]), i)
  1793. pad_after = (F.tile(pad_after, _tuple_setitem((1,)*ndim, i, pad_width[i][1])),)
  1794. tensor_with_pad = pad_before + (arr,) + pad_after
  1795. arr = concatenate(tensor_with_pad, axis=i)
  1796. return arr
  1797. def _pad_edge(arr, pad_width):
  1798. """pad_edge is equivalent to pad_statistic with stat_lenght=1, used in mode:"edge"."""
  1799. def identity_op(arr, axis):
  1800. return arr
  1801. return _pad_statistic(arr, pad_width, 1, identity_op)
  1802. def _pad_wrap(arr, pad_width):
  1803. """The behaviour of wrap mode is consistent with jax.numpy, used in mode:"wrap"."""
  1804. ndim = arr.ndim
  1805. shape = arr.shape
  1806. for i in range(ndim):
  1807. padsize_before = pad_width[i][0] % shape[i]
  1808. padsize_after = pad_width[i][1] % shape[i]
  1809. total_repeats = pad_width[i][0] // shape[i] + 1 + pad_width[i][1] // shape[i]
  1810. tensor_with_pad = ()
  1811. # To avoid any memory issues, we don't make tensor with 0s in their shapes
  1812. if padsize_before > 0:
  1813. tensor_with_pad += (_slice_along_axis(arr, i, shape[i]-padsize_before, shape[i]),)
  1814. tensor_with_pad += (F.tile(arr, _tuple_setitem((1,)*ndim, i, total_repeats)),)
  1815. if padsize_after > 0:
  1816. tensor_with_pad += (_slice_along_axis(arr, i, 0, padsize_after),)
  1817. arr = concatenate(tensor_with_pad, axis=i)
  1818. return arr
  1819. def _pad_linear(arr, pad_width, end_values):
  1820. """Pads the arr with linear range values, used in mode: "linear_ramp"."""
  1821. ndim = arr.ndim
  1822. shape = arr.shape
  1823. dtype = arr.dtype
  1824. end_values = _convert_pad_to_nd(end_values, ndim)
  1825. for i in range(ndim):
  1826. left_value = _slice_along_axis(arr, i, 0, 1)
  1827. right_value = _slice_along_axis(arr, i, shape[i]-1, shape[i])
  1828. pad_before = ()
  1829. pad_after = ()
  1830. if pad_width[i][0] > 0:
  1831. pad_before = (linspace(end_values[i][0], left_value, num=pad_width[i][0],
  1832. endpoint=False, dtype=dtype, axis=i).squeeze(i+1),)
  1833. if pad_width[i][1] > 0:
  1834. pad_after = linspace(right_value, end_values[i][1], num=pad_width[i][1]+1,
  1835. endpoint=True, dtype=dtype, axis=i).squeeze(i+1)
  1836. pad_after = (_slice_along_axis(pad_after, i, 1, pad_width[i][1]+1),)
  1837. tensor_with_pad = pad_before + (arr,) + pad_after
  1838. arr = concatenate(tensor_with_pad, axis=i)
  1839. return arr
  1840. def _add_pads_before(arr, pad_args, mode):
  1841. """handle pads before the array"""
  1842. idx, array_length, times_to_pad_before, additional_pad_before, reflect_type = pad_args
  1843. curr_pad = None
  1844. endpoint_adder = None
  1845. edge_before = _slice_along_axis(arr, idx, 0, 1)
  1846. if mode == "reflect":
  1847. endpoint_adder = 1
  1848. else:
  1849. endpoint_adder = 0
  1850. # Deal with paddings before the original array
  1851. for times in range(times_to_pad_before):
  1852. if times < times_to_pad_before - 1:
  1853. endpoint = array_length
  1854. else:
  1855. endpoint = additional_pad_before + endpoint_adder
  1856. if endpoint != endpoint_adder:
  1857. curr_pad = _slice_along_axis(arr, idx, endpoint_adder, endpoint)
  1858. curr_pad = flip(curr_pad, axis=idx)
  1859. if reflect_type == "odd":
  1860. curr_pad = 2 * edge_before - curr_pad
  1861. arr = P.Concat(idx)((curr_pad, arr))
  1862. edge_before = _slice_along_axis(arr, idx, 0, 1)
  1863. return arr
  1864. def _add_pads_after(arr, pad_args, mode):
  1865. """handle pads after the array"""
  1866. idx, array_length, times_to_pad_after, additional_pad_after, reflect_type = pad_args
  1867. curr_pad = None
  1868. endpoint_adder = None
  1869. edge_end = _slice_along_axis(arr, idx, arr.shape[idx]-1, arr.shape[idx])
  1870. if mode == "reflect":
  1871. endpoint_adder = 1
  1872. else:
  1873. endpoint_adder = 0
  1874. # Deal with paddings after the original array
  1875. for times in range(times_to_pad_after):
  1876. if times < times_to_pad_after - 1:
  1877. startpoint = arr.shape[idx] - array_length
  1878. else:
  1879. startpoint = arr.shape[idx] - additional_pad_after - endpoint_adder
  1880. if startpoint != arr.shape[idx] - endpoint_adder:
  1881. curr_pad = _slice_along_axis(arr, idx, startpoint, arr.shape[idx] - endpoint_adder)
  1882. curr_pad = flip(curr_pad, axis=idx)
  1883. if reflect_type == "odd":
  1884. curr_pad = 2 * edge_end - curr_pad
  1885. arr = P.Concat(idx)((arr, curr_pad))
  1886. edge_end = _slice_along_axis(arr, idx, arr.shape[idx]-1, arr.shape[idx])
  1887. return arr
  1888. def _pad_symmetric(arr, pad_width, reflect_type):
  1889. """pad the array with symmetric paddings"""
  1890. for i in range(arr.ndim):
  1891. array_length = arr.shape[i]
  1892. has_pad_before = (pad_width[i][0] > 0)
  1893. has_pad_after = (pad_width[i][1] > 0)
  1894. times_to_pad_before = pad_width[i][0] // array_length + 1
  1895. additional_pad_before = pad_width[i][0] % array_length
  1896. times_to_pad_after = pad_width[i][1] // array_length + 1
  1897. additional_pad_after = pad_width[i][1] % array_length
  1898. if has_pad_before:
  1899. # Deal with paddings before the original array
  1900. pad_args = (i, array_length, times_to_pad_before, additional_pad_before, reflect_type)
  1901. arr = _add_pads_before(arr, pad_args, "symmetric")
  1902. if has_pad_after:
  1903. # Deal with paddings after the original array
  1904. pad_args = (i, array_length, times_to_pad_after, additional_pad_after, reflect_type)
  1905. arr = _add_pads_after(arr, pad_args, "symmetric")
  1906. return arr
  1907. def _pad_reflect(arr, pad_width, reflect_type):
  1908. """
  1909. pad the array with reflect paddings, this is very similar to symmetric paddings,
  1910. but differs at how edges are selected.
  1911. """
  1912. for i in range(arr.ndim):
  1913. array_length = arr.shape[i]
  1914. if array_length == 1:
  1915. total_repeats = pad_width[i][0] + pad_width[i][1] + 1
  1916. arr = F.tile(arr, _tuple_setitem((1,)*arr.ndim, i, total_repeats))
  1917. else:
  1918. has_pad_before = (pad_width[i][0] > 0)
  1919. has_pad_after = (pad_width[i][1] > 0)
  1920. pad_size = array_length - 1
  1921. times_to_pad_before = pad_width[i][0] // pad_size + 1
  1922. additional_pad_before = pad_width[i][0] % pad_size
  1923. times_to_pad_after = pad_width[i][1] // pad_size + 1
  1924. additional_pad_after = pad_width[i][1] % pad_size
  1925. if has_pad_before:
  1926. # Deal with paddings before the original array
  1927. pad_args = (i, array_length, times_to_pad_before, additional_pad_before, reflect_type)
  1928. arr = _add_pads_before(arr, pad_args, "reflect")
  1929. if has_pad_after:
  1930. # Deal with paddings after the original array
  1931. pad_args = (i, array_length, times_to_pad_after, additional_pad_after, reflect_type)
  1932. arr = _add_pads_after(arr, pad_args, "reflect")
  1933. return arr
  1934. def _pad_func(arr, pad_width, func, **kwargs):
  1935. """applies padding function over different axis."""
  1936. # first creates a padded array with fixed length.
  1937. arr_dim = arr.ndim
  1938. pad_width = _convert_pad_to_nd(pad_width, arr_dim)
  1939. arr = _pad_empty(arr, pad_width)
  1940. for i in range(arr_dim):
  1941. # function signature: padding_func(tensor, iaxis_pad_width, iaxis, kwargs)
  1942. arr = apply_along_axis(func, i, arr, pad_width[i], i, kwargs)
  1943. return arr
  1944. @constexpr
  1945. def _make_stat_length(shape):
  1946. """converts the stat_length values."""
  1947. return tuple((shape[i], shape[i]) for i, _ in enumerate(shape))
  1948. @constexpr
  1949. def _limit_stat_length(stat_length, shape):
  1950. """limits the stat_length to current array length along given dimension."""
  1951. return tuple((min(stat_pair[0], shape[i]), min(stat_pair[1], shape[i])) for i, stat_pair in enumerate(stat_length))
  1952. @constexpr
  1953. def _convert_pad_to_nd(pad_values, ndim):
  1954. """broadcasts the pad_values to (ndim * 2)"""
  1955. if not isinstance(pad_values, (int, list, tuple, Tensor)):
  1956. raise TypeError(
  1957. "pad_width, stat_length, constant_values or end_values should only be int, list, tuple or tensor")
  1958. pad_tensor = _to_tensor(pad_values)
  1959. pad_shape = pad_tensor.shape
  1960. if not pad_shape:
  1961. pad_values = tuple((((pad_values,) * 2) for i in range(ndim)))
  1962. elif pad_shape == (1,):
  1963. pad_values = tuple((tuple(pad_values) * 2) for i in range(ndim))
  1964. elif pad_shape == (2,):
  1965. pad_values = tuple(tuple(pad_values) for i in range(ndim))
  1966. elif pad_shape == (1, 2):
  1967. pad_values = tuple(tuple(pad_values[0]) for i in range(ndim))
  1968. elif pad_shape == (ndim, 2):
  1969. pad_values = tuple(tuple(pad_pair) for pad_pair in pad_values)
  1970. else:
  1971. raise ValueError(f"input values must be able to broadcast to {(ndim, 2)}")
  1972. return pad_values
  1973. def pad(arr, pad_width, mode="constant", stat_length=None, constant_values=0,
  1974. end_values=0, reflect_type="even", **kwargs):
  1975. """
  1976. Pads an array.
  1977. Note:
  1978. Currently, `median` mode is not supported. `reflect` and `symmetric` mode
  1979. only supports GPU backend.
  1980. Args:
  1981. arr (Union[list, tuple, Tensor]): The array to pad.
  1982. pad_width (Union[int, tuple, list]): Number of values padded to the edges of
  1983. each axis. :class:`((before_1, after_1), ... (before_N, after_N))` creates
  1984. unique pad widths for each axis. :class:`((before, after),)` yields same
  1985. before and after pad for each axis. :class:`(pad,)` or int is a shortcut
  1986. for :class:`before = after = pad width` for all axes.
  1987. mode (string, optional):
  1988. One of the following string values:
  1989. - constant (default): Pads with a constant value.
  1990. - edge: Pads with the edge values of `arr`.
  1991. - linear_ramp: Pads with the linear ramp between end_value and the `arr` edge value.
  1992. - maximum: Pads with the maximum value of all or part of the vector along each axis.
  1993. - mean: Pads with the mean value of all or part of the vector along each axis.
  1994. - median: Pads with the median value of all or part of the vector along each axis.
  1995. - minimum: Pads with the minimum value of all or part of the vector along each axis.
  1996. - reflect: Pads with the reflection of the vector mirrored on the first
  1997. and last values of the vector along each axis.
  1998. - symmetric: Pads with the reflection of the vector mirrored along the edge
  1999. of the `arr`.
  2000. - wrap: Pads with the wrap of the vector along the axis. The first values
  2001. are used to pad the end and the end values are used to pad the beginning.
  2002. - empty: Pads with undefined values.
  2003. - <function>: The padding function, if used, should modify and return a new 1-d tensor.
  2004. It has the following signature: :class:`padding_func(tensor, iaxis_pad_width, iaxis, kwargs)`
  2005. stat_length (Union[tuple, list, int], optional): Used in \'maximum\', \'mean\',
  2006. \'median\', and \'minimum\'. Number of values at edge of each axis used
  2007. to calculate the statistic value. :class:`((before_1, after_1), ... (before_N, after_N))`
  2008. creates unique statistic lengths for each axis. :class:`((before, after),)`
  2009. yields same before and after statistic lengths for each axis. :class:`(stat_length,)`
  2010. or int is a shortcut for :class:`before = after = statistic length` for all
  2011. axes. Default is :class:`None`, to use the entire axis.
  2012. constant_values (Union[tuple, list, int], optional):
  2013. Used in :class:`constant mode`. The values to set the padded values for each
  2014. axis. :class:`((before_1, after_1), ... (before_N, after_N))` creates unique pad
  2015. constants for each axis. :class:`((before, after),)` yields same before and
  2016. after constants for each axis. :class:`(constant,)` or :class:`constant` is
  2017. a shortcut for :class:`before = after = constant` for all axes. Default is 0.
  2018. end_values (Union[tuple, list, int], optional): Used in 'linear_ramp'. The values
  2019. used for the ending value of the linear_ramp and that will form the edge of
  2020. the padded `arr`. :class:`((before_1, after_1), ... (before_N, after_N))`
  2021. unique end values for each axis. :class:`((before, after),)` yields same before
  2022. and after end values for each axis. :class:`(constant,)` or :class:`constant`
  2023. is a shortcut for :class:`before = after = constant` for all axes. Default is 0.
  2024. reflect_type(string, optional) can choose between \'even\' and \'odd\'. Used in
  2025. \'reflect\', and \'symmetric\'. The \'even\' style is the default with an
  2026. unaltered reflection around the edge value. For the \'odd\' style, the extended
  2027. part of the `arr` is created by subtracting the reflected values from two times
  2028. the edge value.
  2029. Returns:
  2030. Padded tensor of rank equal to `arr` with shape increased according to `pad_width`.
  2031. Raises:
  2032. TypeError: if `arr`, `pad_width`, `stat_length`, `constant_values` or `end_values`
  2033. have types not specified above.
  2034. ValueError: if `mode` cannot be recognized, or if `pad_width`, `stat_length`,
  2035. `constant_values`, `end_values` cannot broadcast to :class:`(arr.ndim, 2)`,
  2036. or if keyword arguments got unexpected inputs.
  2037. NotImplementedError: if mode is function or '/median'/.
  2038. Supported Platforms:
  2039. ``Ascend`` ``GPU`` ``CPU``
  2040. Examples:
  2041. >>> import mindspore.numpy as np
  2042. >>> tensor = np.array([1., 2., 3., 4., 5.])
  2043. >>> print(np.pad(tensor, (3, 4)))
  2044. [0. 0. 0. 1. 2. 3. 4. 5. 0. 0. 0. 0.]
  2045. >>> print(np.pad(tensor, (3, 4), mode="wrap"))
  2046. [3. 4. 5. 1. 2. 3. 4. 5. 1. 2. 3. 4.]
  2047. >>> print(np.pad(tensor, (3, 4), mode="linear_ramp", end_values=(10, 10)))
  2048. [10. 7. 4. 1. 2. 3. 4. 5. 6.25 7.5 8.75 10. ]
  2049. """
  2050. arr = _to_tensor(arr)
  2051. if arr.ndim == 0:
  2052. return arr
  2053. pad_width = _convert_pad_to_nd(pad_width, arr.ndim)
  2054. stat_func = {"maximum": _reduce_max_keepdims,
  2055. "minimum": _reduce_min_keepdims,
  2056. "mean": _reduce_mean_keepdims,
  2057. "median": "not implemented"}
  2058. if mode not in ("constant", "maximum", "minimum", "mean", "median", "edge",
  2059. "wrap", "linear_ramp", "symmetric", "reflect", "empty") and \
  2060. not _callable(arr, mode):
  2061. _raise_value_error("Input mode not supported.")
  2062. if mode == "constant":
  2063. constant_values = _convert_pad_to_nd(constant_values, arr.ndim)
  2064. return _pad_constant(arr, pad_width, constant_values)
  2065. if mode in ("maximum", "minimum", "mean", "median"):
  2066. # support median mode once P.Sort/P.Median is supported on GPU/CPU
  2067. if mode == "median":
  2068. _raise_unimplemented_error("median mode is not supported yet")
  2069. return _pad_statistic(arr, pad_width, stat_length, stat_func[mode])
  2070. if mode == "edge":
  2071. return _pad_edge(arr, pad_width)
  2072. if mode == "wrap":
  2073. return _pad_wrap(arr, pad_width)
  2074. if mode == "linear_ramp":
  2075. return _pad_linear(arr, pad_width, end_values)
  2076. if mode == "symmetric":
  2077. return _pad_symmetric(arr, pad_width, reflect_type)
  2078. if mode == "reflect":
  2079. return _pad_reflect(arr, pad_width, reflect_type)
  2080. if mode == 'empty':
  2081. return _pad_empty(arr, pad_width)
  2082. return _pad_func(arr, pad_width, mode, **kwargs)