未验证 提交 9215ad96 编写于 作者: S Steffy-zxf 提交者: GitHub

Update code examples for api2.0

Update code examples for api2.0 
上级 1d95a0fb
develop 1.8.5 2.0.1-rocm-post 2.4.1 Ligoml-patch-1 OliverLPH-patch-1 OliverLPH-patch-2 PaddlePM-patch-1 PaddlePM-patch-2 ZHUI-patch-1 add_default_att add_kylinv10 add_model_benchmark_ci add_some_yaml_config addfile all_new_design_exec ascendrc ascendrelease bugfix-eval-frame-leakgae cherry-pick-fix-customOP-random-fail cherry_undefined_var compile_windows cp_2.4_fix_numpy 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-run-program-grad-node-mem fix_check fix_concat_slice fix_custom_device_copy_sync fix_dataloader_memory_leak fix_dlpack_for fix_imperative_dygraph_error fix_newexe_gc fix_npu_ci fix_op_flops fix_retry_ci fix_rnn_docs fix_tensor_type fix_undefined_var fix_var_stop_gradient_error fixiscan fixiscan1 fixiscan2 fixiscan3 hack_event improve_sccache incuabte/new_frl incubate/frl_train_eval incubate/infrt incubate/new_frl incubate/new_frl_rc incubate/stride inplace_addto layer_norm make_flag_adding_easier matmul_double_grad 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 operator_opt paralleltest pass-compile-eval-frame preln_ernie prv-disable-more-cache prv-md-even-more prv-onednn-2.5 prv-reshape-mkldnn-ut2 pten_tensor_refactor release-deleted/2.5 release-rc/2.5 release/2.0 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 release/2.5 release/llm_2.5 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 revert-47325-remove_cudnn_hardcode revert-47645-add_npu_storage_dims revert-48815-set_free_when_no_cache_hit_default_value_true revert-49499-test_ninja_on_ci revert-49654-prim_api_gen revert-49673-modify_get_single_cov revert-49763-fix_static_composite_gen revert-50158-fix_found_inf_bug_for_custom_optimizer revert-50188-refine_optimizer_create_accumulators revert-50335-fix_optminizer_set_auxiliary_var_bug revert-51676-flag_delete revert-51850-fix_softmaxce_dev revert-52175-dev_peak_memory revert-52186-deve revert-52523-test_py38 revert-52912-develop revert-53248-set_cmake_policy revert-54029-fix_windows_compile_bug revert-54068-support_translating_op_attribute revert-54214-modify_cmake_dependencies revert-54370-offline_pslib revert-54391-fix_cmake_md5error revert-54411-fix_cpp17_compile revert-54466-offline_pslib revert-54480-cmake-rocksdb revert-55568-fix_BF16_bug1 revert-56328-new_ir_support_vector_type_place_transfer revert-56366-fix_openssl_bug revert-56545-revert-56366-fix_openssl_bug revert-56620-fix_new_ir_ocr_bug revert-56925-check_inputs_grad_semantic revert-57005-refine_stride_flag rocm_dev_0217 sd_conv_linear_autocast semi-auto/rule-base support-0D-sort support_weight_transpose test_benchmark_ci test_for_Filtetfiles test_model_benchmark test_model_benchmark_ci zhiqiu-patch-1 v2.5.1 v2.5.0 v2.5.0-rc1 v2.5.0-rc0 v2.4.2 v2.4.1 v2.4.0 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
无相关合并请求
...@@ -8670,10 +8670,6 @@ def random_crop(x, shape, seed=None): ...@@ -8670,10 +8670,6 @@ def random_crop(x, shape, seed=None):
def log(x, name=None): def log(x, name=None):
""" """
:alias_main: paddle.log
:alias: paddle.log,paddle.tensor.log,paddle.tensor.math.log
:old_api: paddle.fluid.layers.log
Calculates the natural log of the given input tensor, element-wise. Calculates the natural log of the given input tensor, element-wise.
.. math:: .. math::
...@@ -8681,31 +8677,23 @@ def log(x, name=None): ...@@ -8681,31 +8677,23 @@ def log(x, name=None):
Out = \\ln(x) Out = \\ln(x)
Args: Args:
x (Variable): Input LoDTensor or Tensor. Must be one of the following types: float32, float64. x (Tensor): Input Tensor. Must be one of the following types: float32, float64.
name (str|None): 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` name (str|None): 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: Returns:
Variable: The natural log of the input LoDTensor or Tensor computed element-wise. Tensor: The natural log of the input Tensor computed element-wise.
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle.fluid as fluid import paddle
import numpy as np
# Graph Organizing
x = fluid.layers.data(name="x", shape=[1], dtype="float32")
res = fluid.layers.log(x)
# Create an executor using CPU as an example
exe = fluid.Executor(fluid.CPUPlace())
# Execute x = [[2,3,4], [7,8,9]]
x_i = np.array([[1], [2]]).astype(np.float32) x = paddle.to_tensor(x, dtype='float32')
res_val, = exe.run(fluid.default_main_program(), feed={'x':x_i}, fetch_list=[res]) res = paddle.log(x)
print(res_val) # [[0.], [0.6931472]] # [[0.693147, 1.09861, 1.38629], [1.94591, 2.07944, 2.19722]]
""" """
if in_dygraph_mode(): if in_dygraph_mode():
return core.ops.log(x) return core.ops.log(x)
...@@ -8846,33 +8834,36 @@ def mean_iou(input, label, num_classes): ...@@ -8846,33 +8834,36 @@ def mean_iou(input, label, num_classes):
Parameters: Parameters:
input (Variable): A n-D Tensor of prediction results for semantic labels with type int32 or int64. input (Tensor): A n-D Tensor of prediction results for semantic labels with type int32 or int64.
label (Variable): A Tensor of ground truth labels with type int32 or int64. label (Tensor): A Tensor of ground truth labels with type int32 or int64.
Its shape should be the same as input. Its shape should be the same as input.
num_classes (int32): The possible number of labels. num_classes (int32): The possible number of labels.
Returns: Returns:
Three Variables. Three Tensors.
- mean_iou(Variable) : A 1-D Tensor representing the mean intersection-over-union with shape [1]. \ - mean_iou(Tensor) : A 1-D Tensor representing the mean intersection-over-union with shape [1]. \
Data type is float32. Data type is float32.
- out_wrong(Variable) : A 1-D Tensor with shape [num_classes]. Data type is int32. \ - out_wrong(Tensor) : A 1-D Tensor with shape [num_classes]. Data type is int32. \
The wrong numbers of each class. The wrong numbers of each class.
- out_correct(Variable): A 1-D Tensor with shape [num_classes]. Data type is int32. The correct numbers of each class. - out_correct(Tensor): A 1-D Tensor with shape [num_classes]. Data type is int32. The correct numbers of each class.
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle.fluid as fluid import paddle
iou_shape = [None, 32, 32]
iou_shape = [64, 32, 32]
num_classes = 5 num_classes = 5
predict = fluid.data(name='predict', shape=iou_shape, dtype='int64') predict = paddle.randint(low=0, high=255, shape=iou_shape, dtype='int64')
label = fluid.data(name='label', shape=iou_shape, dtype='int64') label = paddle.randint(low=0, high=255, shape=iou_shape, dtype='int64')
mean_iou, out_wrong, out_correct = fluid.layers.mean_iou(predict, label, mean_iou, out_wrong, out_correct = paddle.metric.mean_iou(predict, label, num_classes)
num_classes)
""" """
if in_dygraph_mode():
return core.ops.mean_iou(input, label, 'num_classes', num_classes)
helper = LayerHelper('mean_iou', **locals()) helper = LayerHelper('mean_iou', **locals())
check_variable_and_dtype(input, 'Predictions', ['int32', 'int64'], check_variable_and_dtype(input, 'Predictions', ['int32', 'int64'],
'mean_iou') 'mean_iou')
...@@ -11387,10 +11378,6 @@ def _elementwise_op(helper): ...@@ -11387,10 +11378,6 @@ def _elementwise_op(helper):
def scale(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None): def scale(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None):
""" """
:alias_main: paddle.scale
:alias: paddle.scale,paddle.tensor.scale,paddle.tensor.math.scale
:old_api: paddle.fluid.layers.scale
Scale operator. Scale operator.
Putting scale and bias to the input Tensor as following: Putting scale and bias to the input Tensor as following:
...@@ -11406,52 +11393,33 @@ def scale(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None): ...@@ -11406,52 +11393,33 @@ def scale(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None):
Out=scale*(X+bias) Out=scale*(X+bias)
Args: Args:
x(Variable): Input N-D Tensor of scale operator. Data type can be float32, float64, int8, int16, int32, int64, uint8. x(Tensor): Input N-D Tensor of scale operator. Data type can be float32, float64, int8, int16, int32, int64, uint8.
scale(float|Variable): The scale factor of the input, it should be a float number or a Variable with shape [1] and data type as float32. scale(float|Tensor): The scale factor of the input, it should be a float number or a Tensor with shape [1] and data type as float32.
bias(float): The bias to be put on the input. bias(float): The bias to be put on the input.
bias_after_scale(bool): Apply bias addition after or before scaling. It is useful for numeric stability in some circumstances. bias_after_scale(bool): Apply bias addition after or before scaling. It is useful for numeric stability in some circumstances.
act(str, optional): Activation applied to the output such as tanh, softmax, sigmoid, relu. act(str, optional): Activation applied to the output such as tanh, softmax, sigmoid, relu.
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` 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: Returns:
Variable(Tensor|LoDTensor): Output tensor of scale operator, with shape and data type same as input. Tensor: Output tensor of scale operator, with shape and data type same as input.
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle.fluid as fluid # scale as a float32 number
import numpy as np import paddle
inputs = fluid.layers.data(name="x", shape=[2, 3], dtype='float32')
output = fluid.layers.scale(inputs, scale = 2.0, bias = 1.0)
exe = fluid.Executor(fluid.CPUPlace())
exe.run(fluid.default_startup_program())
img = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)
res = exe.run(fluid.default_main_program(), feed={'x':img}, fetch_list=[output]) data = paddle.randn(shape=[2,3], dtype='float32')
print(res) # [array([[ 3., 5., 7.], [ 9., 11., 13.]], dtype=float32)] res = paddle.scale(data, scale=2.0, bias=1.0)
.. code-block:: python .. code-block:: python
# scale with parameter scale as Variable # scale with parameter scale as a Tensor
import paddle.fluid as fluid import paddle
import numpy as np
inputs = fluid.layers.data(name="x", shape=[2, 3], dtype='float32')
scale = fluid.layers.data(name="scale", shape=[1], dtype='float32',
append_batch_size=False)
output = fluid.layers.scale(inputs, scale = scale, bias = 1.0)
exe = fluid.Executor(fluid.CPUPlace())
exe.run(fluid.default_startup_program())
img = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)
scale_np = np.array([2.]).astype(np.float32)
res = exe.run(fluid.default_main_program(), feed={'x':img, 'scale':scale_np}, fetch_list=[output]) data = paddle.randn(shape=[2, 3], dtype='float32')
print(res) # [array([[ 3., 5., 7.], [ 9., 11., 13.]], dtype=float32)] factor = paddle.to_tensor([2], dtype='float32')
res = paddle.scale(data, scale=factor, bias=1.0)
""" """
......
...@@ -190,11 +190,9 @@ Examples: ...@@ -190,11 +190,9 @@ Examples:
.. code-block:: python .. code-block:: python
import paddle import paddle
paddle.disable_static()
x = paddle.to_tensor([0.1, 0.2, 0.3, 0.4]) x = paddle.to_tensor([0.1, 0.2, 0.3, 0.4])
out = paddle.rsqrt(x) out = paddle.rsqrt(x)
print(out.numpy())
# [3.16227766 2.23606798 1.82574186 1.58113883] # [3.16227766 2.23606798 1.82574186 1.58113883]
""") """)
......
...@@ -1237,26 +1237,26 @@ def load_combine(out, file_path): ...@@ -1237,26 +1237,26 @@ def load_combine(out, file_path):
def has_inf(x): def has_inf(x):
""" """
:alias_main: paddle.has_inf
:alias: paddle.has_inf,paddle.tensor.has_inf,paddle.tensor.search.has_inf
:old_api: paddle.fluid.layers.has_inf
Test if any of x contains an infinity number Test if any of x contains an infinity number
Args: Args:
x (Variable): The Tensor/LoDTensor to be checked. x (Tensor): The Tensor to be checked.
Returns: Returns:
Variable: The tensor variable storing the output, only a bool value, indicating that whether there is infinity number in x or not. Tensor: The tensor storing the output, only a bool value, indicating that whether there is infinity number in x or not.
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle.fluid as fluid import paddle
data = fluid.layers.data(name="input", shape=[4, 32, 32], dtype="float32") data = paddle.randn(shape=[4, 32, 32], dtype="float32")
res = fluid.layers.has_inf(data) res = paddle.has_inf(data)
# [False]
""" """
if in_dygraph_mode():
return core.ops.isinf(x)
check_type(x, 'x', (Variable), 'has_inf') check_type(x, 'x', (Variable), 'has_inf')
helper = LayerHelper("isinf", **locals()) helper = LayerHelper("isinf", **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype) out = helper.create_variable_for_type_inference(dtype=x.dtype)
...@@ -1266,26 +1266,26 @@ def has_inf(x): ...@@ -1266,26 +1266,26 @@ def has_inf(x):
def has_nan(x): def has_nan(x):
""" """
:alias_main: paddle.has_nan
:alias: paddle.has_nan,paddle.tensor.has_nan,paddle.tensor.search.has_nan
:old_api: paddle.fluid.layers.has_nan
Test if any of x contains a NAN Test if any of x contains a NAN
Args: Args:
x (Variable): The Tensor/LoDTensor to be checked. x (Tensor): The Tensor to be checked.
Returns: Returns:
Variable: The tensor variable storing the output, only a bool value, indicating that whether there is NAN in x or not. Tensor: The tensor variable storing the output, only a bool value, indicating that whether there is NAN in x or not.
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle.fluid as fluid import paddle
data = fluid.layers.data(name="input", shape=[4, 32, 32], dtype="float32") data = paddle.randn(shape=[2,3], dtype="float32")
res = fluid.layers.has_nan(data) res = paddle.has_nan(data)
# [False]
""" """
if in_dygraph_mode():
return core.ops.isnan(x)
check_type(x, 'x', (Variable), 'has_nan') check_type(x, 'x', (Variable), 'has_nan')
helper = LayerHelper("isnan", **locals()) helper = LayerHelper("isnan", **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype) out = helper.create_variable_for_type_inference(dtype=x.dtype)
......
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
import unittest import unittest
import numpy as np import numpy as np
import paddle
import paddle.fluid as fluid import paddle.fluid as fluid
import paddle.fluid.core as core import paddle.fluid.core as core
from op_test import OpTest from op_test import OpTest
...@@ -132,6 +133,14 @@ class BadInputTest(unittest.TestCase): ...@@ -132,6 +133,14 @@ class BadInputTest(unittest.TestCase):
self.assertRaises(TypeError, test_has_nan_bad_x) self.assertRaises(TypeError, test_has_nan_bad_x)
with fluid.dygraph.guard():
data = paddle.zeros([2, 3])
result = paddle.has_inf(data)
expect_value = np.array([False])
self.assertEqual((result.numpy() == expect_value).all(), True)
result = paddle.has_nan(data)
self.assertEqual((result.numpy() == expect_value).all(), True)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()
...@@ -1308,33 +1308,25 @@ def min(x, axis=None, keepdim=False, name=None): ...@@ -1308,33 +1308,25 @@ def min(x, axis=None, keepdim=False, name=None):
def log1p(x, name=None): def log1p(x, name=None):
""" """
:alias_main: paddle.log1p
:alias: paddle.log1p,paddle.tensor.log1p,paddle.tensor.math.log1p
Calculates the natural log of the given input tensor, element-wise. Calculates the natural log of the given input tensor, element-wise.
.. math:: .. math::
Out = \\ln(x+1) Out = \\ln(x+1)
Args: Args:
x (Variable): Input LoDTensor or Tensor. Must be one of the following types: float32, float64. x (Tensor): Input Tensor. Must be one of the following types: float32, float64.
name(str, optional): The default value is None. Normally there is no need for 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` user to set this property. For more information, please refer to :ref:`api_guide_Name`
Returns: Returns:
Variable: The natural log of the input LoDTensor or Tensor computed element-wise. Tensor, the natural log of the input Tensor computed element-wise.
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle import paddle
import paddle.fluid as fluid
import numpy as np data = paddle.to_tensor([[0], [1]], dtype='float32')
# Graph Organizing res = paddle.log1p(data)
x = fluid.data(name="x", shape=[2,1], dtype="float32") # [[0.], [0.6931472]]
res = paddle.log1p(x)
# Create an executor using CPU as an example
exe = fluid.Executor(fluid.CPUPlace())
# Execute
x_i = np.array([[0], [1]]).astype(np.float32)
res_val, = exe.run(fluid.default_main_program(), feed={'x':x_i}, fetch_list=[res])
print(res_val) # [[0.], [0.6931472]]
""" """
if in_dygraph_mode(): if in_dygraph_mode():
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册
反馈
建议
客服 返回
顶部