未验证 提交 9c17b3c9 编写于 作者: W wawltor 提交者: GitHub

Add the max, min, maximum, minimum api for the API 2.0

* Add the max, min, maximum, minimum api for the API 2.0, test=develop
上级 13b80d9b
develop 2.0.1-rocm-post Ligoml-patch-1 OliverLPH-patch-1 OliverLPH-patch-2 PaddlePM-patch-1 PaddlePM-patch-2 ZHUI-patch-1 add_default_att add_model_benchmark_ci add_some_yaml_config addfile all_new_design_exec ascendrc ascendrelease cherry_undefined_var compile_windows delete_2.0.1-rocm-post delete_add_default_att delete_all_new_design_exec delete_ascendrc delete_compile_windows delete_delete_addfile delete_disable_iterable_dataset_unittest delete_fix_dataloader_memory_leak delete_fix_imperative_dygraph_error delete_fix_retry_ci delete_fix_undefined_var delete_improve_sccache delete_paralleltest delete_prv-disable-more-cache delete_revert-31068-fix_conv3d_windows delete_revert-31562-mean delete_revert-33630-bug-fix delete_revert-34159-add_npu_bce_logical_dev delete_revert-34910-spinlocks_for_allocator delete_revert-35069-revert-34910-spinlocks_for_allocator delete_revert-36057-dev/read_flags_in_ut dingjiaweiww-patch-1 disable_iterable_dataset_unittest dy2static enable_eager_model_test final_state_gen_python_c final_state_intermediate fix-numpy-issue fix_concat_slice fix_dataloader_memory_leak fix_imperative_dygraph_error fix_npu_ci fix_op_flops fix_retry_ci fix_rnn_docs fix_tensor_type fix_undefined_var fixiscan fixiscan1 fixiscan2 fixiscan3 github/fork/123malin/netifaces github/fork/123malin/tdm_abacus github/fork/AshburnLee/dev_unique github/fork/ForFishes/fix_memory_matmul github/fork/ForFishes/rm_fluid github/fork/LielinJiang/move-2.0-api github/fork/LielinJiang/visual-dl-cb github/fork/LiuChiachi/add-transformer-generate-square-subsequent-mask-api github/fork/LiuChiachi/fix-example-code-for-hapi-Model github/fork/LiuChiachi/remove-input-requirment-in-dygraph-Model github/fork/MrChengmo/fix_ps_profiler github/fork/MrChengmo/update_ps_heter github/fork/PWhiddy/patch-1 github/fork/Shixiaowei02/dev/save_load_upgrade github/fork/TCChenlong/fix_hapi github/fork/TCChenlong/fix_inden github/fork/Thunderbrook/xpu_slice github/fork/XieYunshen/disable_ut_test_parallel_executor_fetch_isolated_var github/fork/XieYunshen/disable_ut_test_parallel_executor_fetch_isolated_var_3 github/fork/XieYunshen/timeout_20S_ut github/fork/ZeyuChen/remove-nltk github/fork/arlesniak/arlesniak/selective__mkldnn_flags github/fork/baiyfbupt/code_doc_mig github/fork/chalsliu/set_timeout github/fork/chen-zhiyu/develop github/fork/chenwhql/ci/try_to_find_test_buffer_shared_memory_reuse_pass_error github/fork/chenwhql/dygraph/remove_scale_loss_and_apply_collective_grads github/fork/chenwhql/saveload/add_get_inference_program github/fork/chenwhql/saveload/remove_save_load_config github/fork/cryoco/pass-compatibility-trt github/fork/danleifeng/isempty_api2.0 github/fork/frankwhzhang/api_transfer github/fork/hbwx24/error_msg/cuda_kernel_error_msg github/fork/heavengate/cherry_yolo_box github/fork/heavengate/update_yolo_box github/fork/iclementine/rnn_fix github/fork/iducn/testestse github/fork/jczaja/prv-25537-fix github/fork/jiweibo/api_2.0 github/fork/jiweibo/fix_lite_resnet50_test github/fork/juncaipeng/fix_doc_1 github/fork/lfchener/sample_code github/fork/littletomatodonkey/fix_reg_doc github/fork/liym27/dy2stat_update_assign_to_rc20 github/fork/luotao1/profiler_ut github/fork/mapingshuo/add_wait github/fork/mapingshuo/doc_2.0 github/fork/mapingshuo/zero-0.5 github/fork/miraiwk/dev github/fork/pangyoki/add-Categorical-class-branch github/fork/pangyoki/add-multinomial-op-branch github/fork/pangyoki/fix-test_distritbution-CI github/fork/qjing666/doublegrad github/fork/qjing666/fix_hdfs_download github/fork/sandyhouse/add_gather_etc github/fork/sandyhouse/add_send_recv_alltoall_etc github/fork/sandyhouse/pipeline_exe_run github/fork/seiriosPlus/feature/large_scale_kv_save_delta github/fork/seiriosPlus/fix/paddle_errors_fix github/fork/seiriosPlus/fix/paddle_op_errors github/fork/shangzhizhou/fix_test_activation_op_random_bug github/fork/smallv0221/yxp0924 github/fork/smallv0221/yxp0925 github/fork/swtkiwi/del-matplotlib github/fork/tianshuo78520a/kunlun_test github/fork/tianshuo78520a/update_dockerfile github/fork/wanghaoshuang/bert_fuse github/fork/wanghaoshuang/label_smooth github/fork/wanghuancoder/develop_CUDASynchronize github/fork/wanghuancoder/develop_Layer_doc github/fork/wanghuancoder/develop_ParameterList_doc github/fork/wanghuancoder/develop_Sequential_doc github/fork/wanghuancoder/develop_bilinear_tensor_product github/fork/wanghuancoder/develop_coverage_build_sh github/fork/wanghuancoder/develop_in_dynamic_mode_doc github/fork/wanghuancoder/develop_unique_name_doc github/fork/wangxicoding/fleet_meta_combine github/fork/wawltor/error_message_fix_5 github/fork/willthefrog/remove_l2_norm github/fork/windstamp/momentum_op github/fork/windstamp/mv_op_5 github/fork/windstamp/normal_api github/fork/wojtuss/wojtuss/fusion_gru_quantization github/fork/wojtuss/wojtuss/quantization-with-shift github/fork/wzzju/fix_err_info github/fork/wzzju/pure_fp16 github/fork/xiemoyuan/op_error_message github/fork/xiemoyuan/optimize_error_message github/fork/yaoxuefeng6/fix_doc github/fork/yaoxuefeng6/mod_dataset_v2 github/fork/yongqiangma/lod github/fork/ysh329/fix-clip-by-norm-error github/fork/ysh329/fix-error-clip-by-value github/fork/yukavio/error_info github/fork/zhangting2020/conv_filter_grad github/fork/zhangting2020/is_compile_with_cuda github/fork/zhangting2020/place_doc github/fork/zhangting2020/program github/fork/zhhsplendid/fix_any github/fork/zhhsplendid/refine_api2 github/fork/zhhsplendid/refine_api2_test github/fork/zhhsplendid/refine_api_test_ptb_lm github/fork/zhhsplendid/refine_api_test_resnet github/fork/zhhsplendid/refine_api_test_simnet github/fork/zhiqiu/dev/refine_initializer github/fork/zhiqiu/dev/remove_inplace_argument github/fork/zlsh80826/nvinfer_plugin_var_len_cuda11 improve_sccache incubate/infrt inplace_addto make_flag_adding_easier move_embedding_to_phi move_histogram_to_pten move_sgd_to_phi move_slice_to_pten move_temporal_shift_to_phi move_yolo_box_to_phi npu_fix_alloc numel paralleltest preln_ernie prv-disable-more-cache prv-md-even-more prv-onednn-2.5 pten_tensor_refactor release/2.0 release/2.0-beta release/2.0-rc release/2.0-rc1 release/2.1 release/2.2 release/2.3 release/2.3-fc-ernie-fix release/2.4 revert-26856-strategy_example2 revert-27520-disable_pr revert-31068-fix_conv3d_windows revert-31562-mean revert-32290-develop-hardlabel revert-33037-forci revert-33475-fix_cifar_label_dimension revert-33630-bug-fix revert-34159-add_npu_bce_logical_dev revert-34406-add_copy_from_tensor revert-34910-spinlocks_for_allocator revert-35069-revert-34910-spinlocks_for_allocator revert-36057-dev/read_flags_in_ut revert-36201-refine_fast_threaded_ssa_graph_executor revert-36985-add_license revert-37318-refactor_dygraph_to_eager revert-37926-eager_coreops_500 revert-37956-revert-37727-pylayer_support_tuple revert-38100-mingdong revert-38301-allocation_rearrange_pr revert-38703-numpy_bf16_package_reupload revert-38732-remove_useless_header_in_elementwise_mul_grad revert-38959-Reduce_Grad revert-39143-adjust_empty revert-39227-move_trace_op_to_pten revert-39268-dev/remove_concat_fluid_kernel revert-40170-support_partial_grad revert-41056-revert-40727-move_some_activaion_to_phi revert-41065-revert-40993-mv_ele_floordiv_pow revert-41068-revert-40790-phi_new revert-41944-smaller_inference_api_test revert-42149-do-not-reset-default-stream-for-stream-safe-cuda-allocator revert-43155-fix_ut_tempfile revert-43882-revert-41944-smaller_inference_api_test revert-45808-phi/simplify_size_op revert-46827-deform_comment rocm_dev_0217 support_weight_transpose test_benchmark_ci test_feature_precision_test_c test_model_benchmark test_model_benchmark_ci zhiqiu-patch-1 v2.4.0-rc0 v2.3.2 v2.3.1 v2.3.0 v2.3.0-rc0 v2.2.2 v2.2.1 v2.2.0 v2.2.0-rc0 v2.2.0-bak0 v2.1.3 v2.1.2 v2.1.1 v2.1.0 v2.1.0-rc0 v2.0.2 v2.0.1 v2.0.0 v2.0.0-rc1 v2.0.0-rc0 v2.0.0-beta0
无相关合并请求
......@@ -82,7 +82,13 @@ class ElementwiseOp : public framework::OperatorWithKernel {
auto y_dims = ctx->GetInputDim("Y");
int max_dim = std::max(x_dims.size(), y_dims.size());
int axis = ctx->Attrs().Get<int>("axis");
axis = (axis == -1 ? std::abs(x_dims.size() - y_dims.size()) : axis);
PADDLE_ENFORCE_EQ((axis >= (-1 * max_dim)) && (axis < max_dim), true,
platform::errors::InvalidArgument(
"The axis range must be [%s, %s), but axis is %s. "
"Please set the axis again.",
-1 * max_dim, max_dim, axis));
axis = (axis < 0 ? (std::abs(x_dims.size() - y_dims.size()) + axis + 1)
: axis);
std::vector<int> x_dims_array(max_dim);
std::vector<int> y_dims_array(max_dim);
std::vector<int> out_dims_array(max_dim);
......@@ -132,8 +138,7 @@ class ElementwiseOpMaker : public framework::OpProtoAndCheckerMaker {
"Y.dimension must be a subsequence of x.dimension. And axis "
"is the start dimension index "
"for broadcasting Y onto X. ")
.SetDefault(-1)
.EqualGreaterThan(-1);
.SetDefault(-1);
AddAttr<bool>("use_mkldnn", "(bool, default false). Used by MKLDNN.")
.SetDefault(false);
AddAttr<std::string>("x_data_format", "This parameter is no longer used.")
......
......@@ -134,8 +134,6 @@ from .tensor.math import cumsum #DEFINE_ALIAS
from .tensor.math import elementwise_add #DEFINE_ALIAS
from .tensor.math import elementwise_div #DEFINE_ALIAS
from .tensor.math import elementwise_floordiv #DEFINE_ALIAS
from .tensor.math import elementwise_max #DEFINE_ALIAS
from .tensor.math import elementwise_min #DEFINE_ALIAS
from .tensor.math import elementwise_mod #DEFINE_ALIAS
from .tensor.math import elementwise_pow #DEFINE_ALIAS
from .tensor.math import elementwise_sub #DEFINE_ALIAS
......@@ -164,7 +162,9 @@ from .tensor.math import sums #DEFINE_ALIAS
from .tensor.math import tanh #DEFINE_ALIAS
from .tensor.math import elementwise_sum #DEFINE_ALIAS
from .tensor.math import max #DEFINE_ALIAS
from .tensor.math import maximum #DEFINE_ALIAS
from .tensor.math import min #DEFINE_ALIAS
from .tensor.math import minimum #DEFINE_ALIAS
from .tensor.math import mm #DEFINE_ALIAS
from .tensor.math import div #DEFINE_ALIAS
from .tensor.math import multiply #DEFINE_ALIAS
......
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import numpy as np
from op_test import OpTest, skip_check_grad_ci
import paddle
import paddle.fluid.core as core
class ApiMaxTest(unittest.TestCase):
def setUp(self):
if core.is_compiled_with_cuda():
self.place = core.CUDAPlace(0)
else:
self.place = core.CPUPlace()
def test_api(self):
paddle.enable_static()
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data = paddle.nn.data("data", shape=[10, 10], dtype="float32")
result_max = paddle.max(x=data, axis=1)
exe = paddle.static.Executor(self.place)
input_data = np.random.rand(10, 10).astype(np.float32)
res, = exe.run(feed={"data": input_data}, fetch_list=[result_max])
self.assertEqual((res == np.max(input_data, axis=1)).all(), True)
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data = paddle.nn.data("data", shape=[10, 10], dtype="int64")
result_max = paddle.max(x=data, axis=0)
exe = paddle.static.Executor(self.place)
input_data = np.random.randint(10, size=(10, 10)).astype(np.int64)
res, = exe.run(feed={"data": input_data}, fetch_list=[result_max])
self.assertEqual((res == np.max(input_data, axis=0)).all(), True)
def test_errors(self):
paddle.enable_static()
def test_input_type():
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data = np.random.rand(10, 10)
result_max = paddle.max(x=data, axis=0)
self.assertRaises(TypeError, test_input_type)
def test_imperative_api(self):
paddle.disable_static()
np_x = np.array([10, 10]).astype('float64')
x = paddle.to_variable(np_x)
z = paddle.max(x, axis=0)
np_z = z.numpy()
z_expected = np.array(np.max(np_x, axis=0))
self.assertEqual((np_z == z_expected).all(), True)
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import numpy as np
from op_test import OpTest, skip_check_grad_ci
import paddle
import paddle.fluid.core as core
class ApiMaximumTest(unittest.TestCase):
def setUp(self):
if core.is_compiled_with_cuda():
self.place = core.CUDAPlace(0)
else:
self.place = core.CPUPlace()
self.input_x = np.random.rand(10, 15).astype("float32")
self.input_y = np.random.rand(10, 15).astype("float32")
self.input_z = np.random.rand(15).astype("float32")
def test_static_api(self):
paddle.enable_static()
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data_x = paddle.nn.data("x", shape=[10, 15], dtype="float32")
data_y = paddle.nn.data("y", shape=[10, 15], dtype="float32")
result_max = paddle.maximum(data_x, data_y)
exe = paddle.static.Executor(self.place)
res, = exe.run(feed={"x": self.input_x,
"y": self.input_y},
fetch_list=[result_max])
self.assertEqual((res == np.maximum(self.input_x, self.input_y)).all(),
True)
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data_x = paddle.nn.data("x", shape=[10, 15], dtype="float32")
data_z = paddle.nn.data("z", shape=[15], dtype="float32")
result_max = paddle.maximum(data_x, data_z, axis=1)
exe = paddle.static.Executor(self.place)
res, = exe.run(feed={"x": self.input_x,
"z": self.input_z},
fetch_list=[result_max])
self.assertEqual((res == np.maximum(self.input_x, self.input_z)).all(),
True)
def test_dynamic_api(self):
paddle.disable_static()
np_x = np.array([10, 10]).astype('float64')
x = paddle.to_variable(self.input_x)
y = paddle.to_variable(self.input_y)
z = paddle.maximum(x, y)
np_z = z.numpy()
z_expected = np.array(np.maximum(self.input_x, self.input_y))
self.assertEqual((np_z == z_expected).all(), True)
def test_broadcast_axis(self):
paddle.disable_static()
np_x = np.random.rand(5, 4, 3, 2).astype("float64")
np_y = np.random.rand(4, 3).astype("float64")
x = paddle.to_variable(self.input_x)
y = paddle.to_variable(self.input_y)
result_1 = paddle.maximum(x, y, axis=1)
result_2 = paddle.maximum(x, y, axis=-2)
self.assertEqual((result_1.numpy() == result_2.numpy()).all(), True)
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import numpy as np
from op_test import OpTest, skip_check_grad_ci
import paddle
import paddle.fluid.core as core
class ApiMinTest(unittest.TestCase):
def setUp(self):
if core.is_compiled_with_cuda():
self.place = core.CUDAPlace(0)
else:
self.place = core.CPUPlace()
def test_api(self):
paddle.enable_static()
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data = paddle.nn.data("data", shape=[10, 10], dtype="float32")
result_min = paddle.min(x=data, axis=1)
exe = paddle.static.Executor(self.place)
input_data = np.random.rand(10, 10).astype(np.float32)
res, = exe.run(feed={"data": input_data}, fetch_list=[result_min])
self.assertEqual((res == np.min(input_data, axis=1)).all(), True)
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data = paddle.nn.data("data", shape=[10, 10], dtype="int64")
result_min = paddle.min(x=data, axis=0)
exe = paddle.static.Executor(self.place)
input_data = np.random.randint(10, size=(10, 10)).astype(np.int64)
res, = exe.run(feed={"data": input_data}, fetch_list=[result_min])
self.assertEqual((res == np.min(input_data, axis=0)).all(), True)
def test_errors(self):
paddle.enable_static()
def test_input_type():
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data = np.random.rand(10, 10)
result_min = paddle.min(x=data, axis=0)
self.assertRaises(TypeError, test_input_type)
def test_imperative_api(self):
paddle.disable_static()
np_x = np.array([10, 10]).astype('float64')
x = paddle.to_variable(np_x)
z = paddle.min(x, axis=0)
np_z = z.numpy()
z_expected = np.array(np.min(np_x, axis=0))
self.assertEqual((np_z == z_expected).all(), True)
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import numpy as np
from op_test import OpTest, skip_check_grad_ci
import paddle
import paddle.fluid.core as core
class ApiMinimumTest(unittest.TestCase):
def setUp(self):
if core.is_compiled_with_cuda():
self.place = core.CUDAPlace(0)
else:
self.place = core.CPUPlace()
self.input_x = np.random.rand(10, 15).astype("float32")
self.input_y = np.random.rand(10, 15).astype("float32")
self.input_z = np.random.rand(15).astype("float32")
def test_static_api(self):
paddle.enable_static()
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data_x = paddle.nn.data("x", shape=[10, 15], dtype="float32")
data_y = paddle.nn.data("y", shape=[10, 15], dtype="float32")
result_min = paddle.minimum(data_x, data_y)
exe = paddle.static.Executor(self.place)
res, = exe.run(feed={"x": self.input_x,
"y": self.input_y},
fetch_list=[result_min])
self.assertEqual((res == np.minimum(self.input_x, self.input_y)).all(),
True)
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data_x = paddle.nn.data("x", shape=[10, 15], dtype="float32")
data_z = paddle.nn.data("z", shape=[15], dtype="float32")
result_min = paddle.minimum(data_x, data_z, axis=1)
exe = paddle.static.Executor(self.place)
res, = exe.run(feed={"x": self.input_x,
"z": self.input_z},
fetch_list=[result_min])
self.assertEqual((res == np.minimum(self.input_x, self.input_z)).all(),
True)
def test_dynamic_api(self):
paddle.disable_static()
np_x = np.array([10, 10]).astype('float64')
x = paddle.to_variable(self.input_x)
y = paddle.to_variable(self.input_y)
z = paddle.minimum(x, y)
np_z = z.numpy()
z_expected = np.array(np.minimum(self.input_x, self.input_y))
self.assertEqual((np_z == z_expected).all(), True)
def test_broadcast_axis(self):
paddle.disable_static()
np_x = np.random.rand(5, 4, 3, 2).astype("float64")
np_y = np.random.rand(4, 3).astype("float64")
x = paddle.to_variable(self.input_x)
y = paddle.to_variable(self.input_y)
result_1 = paddle.minimum(x, y, axis=1)
result_2 = paddle.minimum(x, y, axis=-2)
self.assertEqual((result_1.numpy() == result_2.numpy()).all(), True)
......@@ -628,69 +628,5 @@ class API_TestSumOp(unittest.TestCase):
self.assertEqual((np_z == z_expected).all(), True)
class API_TestMaxOp(unittest.TestCase):
def test_1(self):
# type: float
with fluid.program_guard(fluid.Program(), fluid.Program()):
data = fluid.data("data", shape=[10, 10], dtype="float32")
result_max = paddle.max(input=data, dim=1)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
input_data = np.random.rand(10, 10).astype(np.float32)
res, = exe.run(feed={"data": input_data}, fetch_list=[result_max])
self.assertEqual((res == np.max(input_data, axis=1)).all(), True)
# type: int
with fluid.program_guard(fluid.Program(), fluid.Program()):
data = fluid.data("data", shape=[10, 10], dtype="int64")
result_max = paddle.max(input=data, dim=1)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
input_data = np.random.randint(10, size=(10, 10)).astype(np.int64)
res, = exe.run(feed={"data": input_data}, fetch_list=[result_max])
self.assertEqual((res == np.max(input_data, axis=1)).all(), True)
# dygraph
with fluid.dygraph.guard():
np_x = np.array([10, 10]).astype('float64')
x = fluid.dygraph.to_variable(np_x)
z = paddle.max(x, dim=0)
np_z = z.numpy()
z_expected = np.array(np.max(np_x, axis=0))
self.assertEqual((np_z == z_expected).all(), True)
class API_TestMinOp(unittest.TestCase):
def test_1(self):
# type: float
with fluid.program_guard(fluid.Program(), fluid.Program()):
data = fluid.data("data", shape=[10, 10], dtype="float32")
result_min = paddle.min(input=data, dim=1)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
input_data = np.random.rand(10, 10).astype(np.float32)
res, = exe.run(feed={"data": input_data}, fetch_list=[result_min])
self.assertEqual((res == np.min(input_data, axis=1)).all(), True)
# type: int
with fluid.program_guard(fluid.Program(), fluid.Program()):
data = fluid.data("data", shape=[10, 10], dtype="int64")
result_min = paddle.min(input=data, dim=1)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
input_data = np.random.randint(10, size=(10, 10)).astype(np.int64)
res, = exe.run(feed={"data": input_data}, fetch_list=[result_min])
self.assertEqual((res == np.min(input_data, axis=1)).all(), True)
# dygraph
with fluid.dygraph.guard():
np_x = np.array([10, 10]).astype('float64')
x = fluid.dygraph.to_variable(np_x)
z = paddle.min(x, dim=0)
np_z = z.numpy()
z_expected = np.array(np.min(np_x, axis=0))
self.assertEqual((np_z == z_expected).all(), True)
if __name__ == '__main__':
unittest.main()
......@@ -110,8 +110,6 @@ from .math import cumsum #DEFINE_ALIAS
from .math import elementwise_add #DEFINE_ALIAS
from .math import elementwise_div #DEFINE_ALIAS
from .math import elementwise_floordiv #DEFINE_ALIAS
from .math import elementwise_max #DEFINE_ALIAS
from .math import elementwise_min #DEFINE_ALIAS
from .math import elementwise_mod #DEFINE_ALIAS
from .math import elementwise_pow #DEFINE_ALIAS
from .math import elementwise_sub #DEFINE_ALIAS
......@@ -140,7 +138,9 @@ from .math import sums #DEFINE_ALIAS
from .math import tanh #DEFINE_ALIAS
from .math import elementwise_sum #DEFINE_ALIAS
from .math import max #DEFINE_ALIAS
from .math import maximum #DEFINE_ALIAS
from .math import min #DEFINE_ALIAS
from .math import minimum #DEFINE_ALIAS
from .math import mm #DEFINE_ALIAS
from .math import div #DEFINE_ALIAS
from .math import multiply #DEFINE_ALIAS
......
......@@ -36,8 +36,6 @@ from ..fluid.layers import cosh #DEFINE_ALIAS
from ..fluid.layers import elementwise_add #DEFINE_ALIAS
from ..fluid.layers import elementwise_div #DEFINE_ALIAS
from ..fluid.layers import elementwise_floordiv #DEFINE_ALIAS
from ..fluid.layers import elementwise_max #DEFINE_ALIAS
from ..fluid.layers import elementwise_min #DEFINE_ALIAS
from ..fluid.layers import elementwise_mod #DEFINE_ALIAS
from ..fluid.layers import elementwise_mul #DEFINE_ALIAS
from ..fluid.layers import elementwise_pow #DEFINE_ALIAS
......@@ -78,8 +76,6 @@ __all__ = [
'elementwise_add',
'elementwise_div',
'elementwise_floordiv',
'elementwise_max',
'elementwise_min',
'elementwise_mod',
'elementwise_pow',
'elementwise_sub',
......@@ -109,7 +105,9 @@ __all__ = [
'tanh',
'elementwise_sum',
'max',
'maximum',
'min',
'minimum',
'mm',
'div',
'multiply',
......@@ -511,13 +509,117 @@ Examples:
return _elementwise_op(LayerHelper(op_type, **locals()))
def maximum(x, y, axis=-1, name=None):
"""
Examples:
.. code-block:: python
import paddle
import numpy as np
paddle.disable_static()
x_data = np.array([[1, 2], [3, 4]], dtype=np.float32)
y_data = np.array([[5, 6], [7, 8]], dtype=np.float32)
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
res = paddle.maximum(x, y)
print(res.numpy())
#[[5. 6.]
# [7. 8.]]
x_data = np.array([[[1, 2, 3], [1, 2, 3]]], dtype=np.float32)
y_data = np.array([1, 2], dtype=np.float32)
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
res = paddle.maximum(x, y, axis=1)
print(res.numpy())
#[[[1. 2. 3.]
# [2. 2. 3.]]]
x_data = np.array([2, 3, 5], dtype=np.float32)
y_data = np.array([1, 4, np.nan], dtype=np.float32)
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
res = paddle.maximum(x, y)
print(res.numpy())
#[ 2. 4. nan]
x_data = np.array([5, 3, np.inf], dtype=np.float32)
y_data = np.array([1, 4, 5], dtype=np.float32)
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
res = paddle.maximum(x, y)
print(res.numpy())
#[ 5. 4. inf]
"""
op_type = 'elementwise_max'
act = None
if in_dygraph_mode():
return _elementwise_op_in_dygraph(
x, y, axis=axis, act=act, op_name=op_type)
return _elementwise_op(LayerHelper(op_type, **locals()))
def minimum(x, y, axis=-1, name=None):
"""
Examples:
.. code-block:: python
import paddle
import numpy as np
paddle.disable_static()
x_data = np.array([[1, 2], [3, 4]], dtype=np.float32)
y_data = np.array([[5, 6], [7, 8]], dtype=np.float32)
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
res = paddle.minimum(x, y)
print(res.numpy())
#[[1. 2.]
# [3. 4.]]
x_data = np.array([[[1, 2, 3], [1, 2, 3]]], dtype=np.float32)
y_data = np.array([1, 2], dtype=np.float32)
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
res = paddle.minimum(x, y, axis=1)
print(res.numpy())
#[[[1. 1. 1.]
# [2. 2. 2.]]]
x_data = np.array([2, 3, 5], dtype=np.float32)
y_data = np.array([1, 4, np.nan], dtype=np.float32)
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
res = paddle.minimum(x, y)
print(res.numpy())
#[ 1. 3. nan]
x_data = np.array([5, 3, np.inf], dtype=np.float32)
y_data = np.array([1, 4, 5], dtype=np.float32)
x = paddle.to_variable(x_data)
y = paddle.to_variable(y_data)
res = paddle.minimum(x, y)
print(res.numpy())
#[1. 3. 5.]
"""
op_type = 'elementwise_min'
act = None
if in_dygraph_mode():
return _elementwise_op_in_dygraph(
x, y, axis=axis, act=act, op_name=op_type)
return _elementwise_op(LayerHelper(op_type, **locals()))
for func in [
add,
div,
multiply,
maximum,
minimum,
multiply
]:
proto_dict = {'add': 'elementwise_add', 'div': 'elementwise_div', 'multiply': 'elementwise_mul'}
proto_dict = {'add': 'elementwise_add', 'div': 'elementwise_div', 'maximum': 'elementwise_max', 'minimum': 'elementwise_min', 'multiply': 'elementwise_mul'}
op_proto = OpProtoHolder.instance().get_op_proto(proto_dict[func.__name__])
if func.__name__ in ['add']:
alias_main = ':alias_main: paddle.%(func)s' % {'func': func.__name__}
......@@ -1065,152 +1167,179 @@ def inverse(input, name=None):
return out
def max(input, dim=None, keep_dim=False, name=None):
def max(x, axis=None, keepdim=False, name=None):
"""
:alias_main: paddle.max
:alias: paddle.max,paddle.tensor.max,paddle.tensor.math.max
Computes the maximum of tensor elements over the given dimension.
Computes the maximum of tensor elements over the given axis.
Args:
input (Variable): The input variable which is a Tensor, the data type is float32,
x(Tensor): A tensor, the data type is float32,
float64, int32, int64.
dim (list|int, optional): The dimension along which the maximum is computed.
axis(list|int, optional): The axis along which the maximum is computed.
If :attr:`None`, compute the maximum over all elements of
:attr:`input` and return a Tensor variable with a single element,
otherwise must be in the range :math:`[-rank(input), rank(input))`.
If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank + dim[i]`.
keep_dim (bool, optional): Whether to reserve the reduced dimension in the
otherwise must be in the range :math:`[-x.ndim(x), x.ndim(x))`.
If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`.
keepdim(bool, optional): Whether to reserve the reduced dimension in the
output Tensor. The result tensor will have one fewer dimension
than the :attr:`input` unless :attr:`keep_dim` is true, default
than the :attr:`input` unless :attr:`keepdim` is true, default
value is False.
name(str, optional): The default value is None. Normally there is no need for
user to set this property. For more information, please refer to :ref:`api_guide_Name`
Returns:
Variable: Tensor, results of maximum on the specified dim of input tensor,
Tensor, results of maximum on the specified axis of input tensor,
it's data type is the same as input's Tensor.
Examples:
.. code-block:: python
import numpy as np
import paddle
import paddle.fluid as fluid
# x is a Tensor variable with following elements:
# [[0.2, 0.3, 0.5, 0.9]
# [0.1, 0.2, 0.6, 0.7]]
# Each example is followed by the corresponding output tensor.
x = fluid.data(name='x', shape=[2, 4], dtype='float32')
paddle.max(x) # [0.9]
paddle.max(x, dim=0) # [0.2, 0.3, 0.6, 0.9]
paddle.max(x, dim=-1) # [0.9, 0.7]
paddle.max(x, dim=1, keep_dim=True) # [[0.9], [0.7]]
# y is a Tensor variable with shape [2, 2, 2] and elements as below:
# [[[1.0, 2.0], [3.0, 4.0]],
# [[5.0, 6.0], [7.0, 8.0]]]
# Each example is followed by the corresponding output tensor.
y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32')
paddle.max(y, dim=[1, 2]) # [4.0, 8.0]
paddle.max(y, dim=[0, 1]) # [7.0, 8.0]
paddle.disable_static()
# data_x is a variable with shape [2, 4]
# the axis is a int element
data_x = np.array([[0.2, 0.3, 0.5, 0.9],
[0.1, 0.2, 0.6, 0.7]])
x = paddle.to_variable(data_x)
result1 = paddle.max(x)
print(result1.numpy())
#[0.9]
result2 = paddle.max(x, axis=0)
print(result2.numpy())
#[0.2 0.3 0.6 0.9]
result3 = paddle.max(x, axis=-1)
print(result3.numpy())
#[0.9 0.7]
result4 = paddle.max(x, axis=1, keepdim=True)
print(result4.numpy())
#[[0.9]
# [0.7]]
# data_y is a variable with shape [2, 2, 2]
# the axis is list
data_y = np.array([[[1.0, 2.0], [3.0, 4.0]],
[[5.0, 6.0], [7.0, 8.0]]])
y = paddle.to_variable(data_y)
result5 = paddle.max(y, axis=[1, 2])
print(result5.numpy())
#[4. 8.]
result6 = paddle.max(y, axis=[0, 1])
print(result6.numpy())
#[7. 8.]
"""
helper = LayerHelper('max', **locals())
out = helper.create_variable_for_type_inference(
dtype=helper.input_dtype())
if dim is not None and not isinstance(dim, list):
dim = [dim]
if axis is not None and not isinstance(axis, list):
axis = [axis]
reduce_all = True if axis == None or axis == [] else False
axis = axis if axis != None and axis != [] else [0]
if in_dygraph_mode():
return core.ops.reduce_max(x, 'dim', axis, 'keep_dim', keepdim,
'reduce_all', reduce_all)
helper = LayerHelper('max', **locals())
check_variable_and_dtype(
input, 'input', ['float32', 'float64', 'int32', 'int64'], 'max')
reduce_all = True if dim == None or dim == [] else False
dim = dim if dim != None and dim != [] else [0]
x, 'x', ['float32', 'float64', 'int32', 'int64'], 'max')
if in_dygraph_mode():
return core.ops.reduce_max(input, 'dim', dim, 'keep_dim', keep_dim,
'reduce_all', reduce_all)
out = helper.create_variable_for_type_inference(
dtype=helper.input_dtype())
helper.append_op(
type='reduce_max',
inputs={'X': input},
inputs={'X': x},
outputs={'Out': out},
attrs={
'dim': dim,
'keep_dim': keep_dim,
'dim': axis,
'keep_dim': keepdim,
'reduce_all': reduce_all
})
return out
def min(input, dim=None, keep_dim=False, name=None):
def min(x, axis=None, keepdim=False, name=None):
"""
:alias_main: paddle.min
:alias: paddle.min,paddle.tensor.min,paddle.tensor.math.min
Computes the minimum of tensor elements over the given dimension.
Computes the minimum of tensor elements over the given axis
Args:
input (Variable): The input variable which is a Tensor, the data type is float32,
float64, int32, int64.
dim (list|int, optional): The dimensions along which the minimum is computed.
x(Tensor): A tensor, the data type is float32, float64, int32, int64.
axis(list|int, optional): The axis along which the minimum is computed.
If :attr:`None`, compute the minimum over all elements of
:attr:`input` and return a Tensor variable with a single element,
otherwise must be in the range :math:`[-rank(input), rank(input))`.
If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank + dim[i]`.
keep_dim (bool, optional): Whether to reserve the reduced dimension in the
otherwise must be in the range :math:`[-x.ndim, x.ndim)`.
If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`.
keepdim(bool, optional): Whether to reserve the reduced dimension in the
output Tensor. The result tensor will have one fewer dimension
than the :attr:`input` unless :attr:`keep_dim` is true, default
than the :attr:`input` unless :attr:`keepdim` is true, default
value is False.
name(str, optional): The default value is None. Normally there is no need for
user to set this property. For more information, please refer to :ref:`api_guide_Name`
Returns:
Variable: Tensor, result of minimum on the specified dim of input tensor,
Tensor, results of minimum on the specified axis of input tensor,
it's data type is the same as input's Tensor.
Examples:
.. code-block:: python
import paddle
import paddle.fluid as fluid
# x is a Tensor variable with following elements:
# [[0.2, 0.3, 0.5, 0.9]
# [0.1, 0.2, 0.6, 0.7]]
# Each example is followed by the corresponding output tensor.
x = fluid.data(name='x', shape=[2, 4], dtype='float32')
paddle.min(x) # [0.1]
paddle.min(x, dim=0) # [0.1, 0.2, 0.5, 0.7]
paddle.min(x, dim=-1) # [0.2, 0.1]
paddle.min(x, dim=1, keep_dim=True) # [[0.2], [0.1]]
# y is a Tensor variable with shape [2, 2, 2] and elements as below:
# [[[1.0, 2.0], [3.0, 4.0]],
# [[5.0, 6.0], [7.0, 8.0]]]
# Each example is followed by the corresponding output tensor.
y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32')
paddle.min(y, dim=[1, 2]) # [1.0, 5.0]
paddle.min(y, dim=[0, 1]) # [1.0, 2.0]
"""
helper = LayerHelper('min', **locals())
out = helper.create_variable_for_type_inference(
dtype=helper.input_dtype())
if dim is not None and not isinstance(dim, list):
dim = [dim]
import numpy as np
import paddle
check_variable_and_dtype(
input, 'input', ['float32', 'float64', 'int32', 'int64'], 'max')
paddle.disable_static()
reduce_all = True if dim == None or dim == [] else False
dim = dim if dim != None and dim != [] else [0]
# data_x is a variable with shape [2, 4]
# the axis is a int element
data_x = np.array([[0.2, 0.3, 0.5, 0.9],
[0.1, 0.2, 0.6, 0.7]])
x = paddle.to_variable(data_x)
result1 = paddle.min(x)
print(result1.numpy())
#[0.1]
result2 = paddle.min(x, axis=0)
print(result2.numpy())
#[0.1 0.2 0.5 0.7]
result3 = paddle.min(x, axis=-1)
print(result3.numpy())
#[0.2 0.1]
result4 = paddle.min(x, axis=1, keepdim=True)
print(result4.numpy())
#[[0.2]
# [0.1]]
# data_y is a variable with shape [2, 2, 2]
# the axis is list
data_y = np.array([[[1.0, 2.0], [3.0, 4.0]],
[[5.0, 6.0], [7.0, 8.0]]])
y = paddle.to_variable(data_y)
result5 = paddle.min(y, axis=[1, 2])
print(result5.numpy())
#[1. 5.]
result6 = paddle.min(y, axis=[0, 1])
print(result6.numpy())
#[1. 2.]
"""
if axis is not None and not isinstance(axis, list):
axis= [axis]
reduce_all = True if axis == None or axis == [] else False
axis = axis if axis != None and axis != [] else [0]
if in_dygraph_mode():
return core.ops.reduce_min(input, 'dim', dim, 'keep_dim', keep_dim,
return core.ops.reduce_min(x, 'dim', axis, 'keep_dim', keepdim,
'reduce_all', reduce_all)
helper = LayerHelper('min', **locals())
check_variable_and_dtype(
x, 'x', ['float32', 'float64', 'int32', 'int64'], 'min')
out = helper.create_variable_for_type_inference(
dtype=helper.input_dtype())
helper.append_op(
type='reduce_min',
inputs={'X': input},
inputs={'X': x},
outputs={'Out': out},
attrs={
'dim': dim,
'keep_dim': keep_dim,
'dim': axis,
'keep_dim': keepdim,
'reduce_all': reduce_all
})
return out
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册
反馈
建议
客服 返回
顶部