logic.py 35.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

15 16
# TODO: define logic functions of a tensor

17
import paddle
18

19
from ..common_ops_import import Variable
20
from ..fluid.data_feeder import check_type, check_variable_and_dtype
21
from ..fluid.framework import global_var
22
from .layer_function_generator import templatedoc
23

24
if global_var._in_eager_mode_:
25
    Tensor = paddle.fluid.framework.core.eager.Tensor
W
Weilong Wu 已提交
26 27
else:
    from ..framework import VarBase as Tensor
28

29
from paddle import _C_ops
30
from paddle.tensor.creation import full
31

32 33
from ..framework import LayerHelper, in_dygraph_mode

34 35
__all__ = []

36

37
def _logical_op(op_name, x, y, out=None, name=None, binary_op=True):
38
    if in_dygraph_mode():
39 40 41 42 43
        op = getattr(_C_ops, op_name)
        if binary_op:
            return op(x, y)
        else:
            return op(x)
44
    else:
45
        check_variable_and_dtype(
46 47
            x,
            "x",
48
            ["bool", "int8", "int16", "int32", "int64", "float32", "float64"],
49 50
            op_name,
        )
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
        if y is not None:
            check_variable_and_dtype(
                y,
                "y",
                [
                    "bool",
                    "int8",
                    "int16",
                    "int32",
                    "int64",
                    "float32",
                    "float64",
                ],
                op_name,
            )
        if out is not None:
            check_type(out, "out", Variable, op_name)
68

69
        helper = LayerHelper(op_name, **locals())
70

71 72 73 74 75
        if binary_op and x.dtype != y.dtype:
            raise ValueError(
                "(InvalidArgument) The DataType of %s Op's Variable must be consistent, but received %s and %s."
                % (op_name, x.dtype, y.dtype)
            )
76

77 78
        if out is None:
            out = helper.create_variable_for_type_inference(dtype=x.dtype)
79

80 81 82 83 84 85 86 87
        if binary_op:
            helper.append_op(
                type=op_name, inputs={"X": x, "Y": y}, outputs={"Out": out}
            )
        else:
            helper.append_op(
                type=op_name, inputs={"X": x}, outputs={"Out": out}
            )
88

89
        return out
90 91 92 93 94


def logical_and(x, y, out=None, name=None):
    r"""

95
    Compute element-wise logical AND on ``x`` and ``y``, and return ``out``. ``out`` is N-dim boolean ``Tensor``.
96 97 98 99 100 101
    Each element of ``out`` is calculated by

    .. math::

        out = x \&\& y

102
    Note:
I
Infinity_lee 已提交
103 104 105
        ``paddle.logical_and`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .

        .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
106 107 108 109

    Args:
        x (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64.
        y (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64.
110
        out(Tensor, optional): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor`` will be created to save the output.
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        N-D Tensor. A location into which the result is stored. It's dimension equals with ``x``.

    Examples:
        .. code-block:: python

            import paddle

            x = paddle.to_tensor([True])
            y = paddle.to_tensor([True, False, True, False])
            res = paddle.logical_and(x, y)
            print(res) # [True False True False]
    """
    if in_dygraph_mode():
127
        return _C_ops.logical_and(x, y)
128

129 130 131
    return _logical_op(
        op_name="logical_and", x=x, y=y, name=name, out=out, binary_op=True
    )
132 133 134 135 136 137 138 139 140 141 142 143


def logical_or(x, y, out=None, name=None):
    """

    ``logical_or`` operator computes element-wise logical OR on ``x`` and ``y``, and returns ``out``. ``out`` is N-dim boolean ``Tensor``.
    Each element of ``out`` is calculated by

    .. math::

        out = x || y

144
    Note:
I
Infinity_lee 已提交
145 146 147
        ``paddle.logical_or`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .

        .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
148

149 150 151 152 153 154 155 156 157 158 159 160 161 162
    Args:
        x (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64.
        y (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64.
        out(Tensor): The ``Variable`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor`` will be created to save the output.
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        N-D Tensor. A location into which the result is stored. It's dimension equals with ``x``.

    Examples:
        .. code-block:: python

            import paddle

163 164
            x = paddle.to_tensor([True, False], dtype="bool").reshape([2, 1])
            y = paddle.to_tensor([True, False, True, False], dtype="bool").reshape([2, 2])
165
            res = paddle.logical_or(x, y)
166 167 168 169
            print(res)
            # Tensor(shape=[2, 2], dtype=bool, place=Place(cpu), stop_gradient=True,
            #        [[True , True ],
            #         [True , False]])
170 171
    """
    if in_dygraph_mode():
172
        return _C_ops.logical_or(x, y)
173 174 175
    return _logical_op(
        op_name="logical_or", x=x, y=y, name=name, out=out, binary_op=True
    )
176 177 178 179 180 181 182 183 184 185 186 187


def logical_xor(x, y, out=None, name=None):
    r"""

    ``logical_xor`` operator computes element-wise logical XOR on ``x`` and ``y``, and returns ``out``. ``out`` is N-dim boolean ``Tensor``.
    Each element of ``out`` is calculated by

    .. math::

        out = (x || y) \&\& !(x \&\& y)

188
    Note:
I
Infinity_lee 已提交
189 190 191
        ``paddle.logical_xor`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .

        .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

    Args:
        x (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64.
        y (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64.
        out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor`` will be created to save the output.
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        N-D Tensor. A location into which the result is stored. It's dimension equals with ``x``.

    Examples:
        .. code-block:: python

            import paddle

207 208
            x = paddle.to_tensor([True, False], dtype="bool").reshape([2, 1])
            y = paddle.to_tensor([True, False, True, False], dtype="bool").reshape([2, 2])
209
            res = paddle.logical_xor(x, y)
210 211 212 213
            print(res)
            # Tensor(shape=[2, 2], dtype=bool, place=Place(cpu), stop_gradient=True,
            #        [[False, True ],
            #         [True , False]])
214 215
    """
    if in_dygraph_mode():
216
        return _C_ops.logical_xor(x, y)
217

218 219 220
    return _logical_op(
        op_name="logical_xor", x=x, y=y, name=name, out=out, binary_op=True
    )
221 222 223 224 225 226 227 228 229 230 231 232 233


@templatedoc()
def logical_not(x, out=None, name=None):
    """

    ``logical_not`` operator computes element-wise logical NOT on ``x``, and returns ``out``. ``out`` is N-dim boolean ``Variable``.
    Each element of ``out`` is calculated by

    .. math::

        out = !x

I
Infinity_lee 已提交
234 235 236 237 238
    Note:
        ``paddle.logical_not`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .

        .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    Args:
        x(Tensor):  Operand of logical_not operator. Must be a Tensor of type bool, int8, int16, in32, in64, float32, or float64.
        out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor` will be created to save the output.
        name(str|None): The default value is None. Normally there is no need for users to set this property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor: ${out_comment}

    Examples:
        .. code-block:: python

            import paddle

            x = paddle.to_tensor([True, False, True, False])
            res = paddle.logical_not(x)
            print(res) # [False  True False  True]
    """
    if in_dygraph_mode():
257
        return _C_ops.logical_not(x)
258 259 260
    return _logical_op(
        op_name="logical_not", x=x, y=None, name=name, out=out, binary_op=False
    )
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294


def is_empty(x, name=None):
    """

    Test whether a Tensor is empty.

    Args:
        x (Tensor): The Tensor to be tested.
        name (str, optional): The default value is ``None`` . Normally users
                            don't have to set this parameter. For more information,
                            please refer to :ref:`api_guide_Name` .

    Returns:
        Tensor: A bool scalar Tensor. True if 'x' is an empty Tensor.

    Examples:
        .. code-block:: python

            import paddle

            input = paddle.rand(shape=[4, 32, 32], dtype='float32')
            res = paddle.is_empty(x=input)
            print("res:", res)
            # ('res:', Tensor: eager_tmp_1
            #    - place: CPUPlace
            #    - shape: [1]
            #    - layout: NCHW
            #    - dtype: bool
            #    - data: [0])

    """
    if in_dygraph_mode():
        return _C_ops.is_empty(x)
295 296 297 298 299
    else:
        check_variable_and_dtype(
            x, 'x', ['float32', 'float64', 'int32', 'int64'], 'is_empty'
        )
        check_type(name, "name", (str, type(None)), "is_empty")
300

301 302 303 304 305 306 307
        helper = LayerHelper("is_empty", **locals())
        cond = helper.create_variable_for_type_inference(dtype='bool')
        cond.stop_gradient = True
        helper.append_op(
            type='is_empty', inputs={'X': [x]}, outputs={'Out': [cond]}
        )
        return cond
308 309


W
wawltor 已提交
310
def equal_all(x, y, name=None):
311
    """
312
    Returns the truth value of :math:`x == y`. True if two inputs have the same elements, False otherwise.
313

314
    Note:
315
        The output has no gradient.
316 317

    Args:
318 319
        x(Tensor): Tensor, data type is bool, float32, float64, int32, int64.
        y(Tensor): Tensor, data type is bool, float32, float64, int32, int64.
W
wawltor 已提交
320 321
        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`.
322 323

    Returns:
W
wawltor 已提交
324
        Tensor: output Tensor, data type is bool, value is [False] or [True].
325 326 327 328 329

    Examples:
        .. code-block:: python

          import paddle
W
wawltor 已提交
330

331 332 333
          x = paddle.to_tensor([1, 2, 3])
          y = paddle.to_tensor([1, 2, 3])
          z = paddle.to_tensor([1, 4, 3])
W
wawltor 已提交
334
          result1 = paddle.equal_all(x, y)
N
Noel 已提交
335
          print(result1) # result1 = [True ]
W
wawltor 已提交
336
          result2 = paddle.equal_all(x, z)
N
Noel 已提交
337
          print(result2) # result2 = [False ]
338
    """
H
hong 已提交
339
    if in_dygraph_mode():
340
        return _C_ops.equal_all(x, y)
341 342 343 344 345 346 347 348 349
    else:
        helper = LayerHelper("equal_all", **locals())
        out = helper.create_variable_for_type_inference(dtype='bool')
        helper.append_op(
            type='equal_all',
            inputs={'X': [x], 'Y': [y]},
            outputs={'Out': [out]},
        )
        return out
Z
Zhen Wang 已提交
350 351 352


@templatedoc()
353
def allclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name=None):
354 355 356 357 358 359 360 361 362
    r"""
    Check if all :math:`x` and :math:`y` satisfy the condition:

    .. math::
        \left| x - y \right| \leq atol + rtol \times \left| y \right|

    elementwise, for all elements of :math:`x` and :math:`y`. The behaviour of this
    operator is analogous to :math:`numpy.allclose`, namely that it returns :math:`True` if
    two tensors are elementwise equal within a tolerance.
Z
Zhen Wang 已提交
363 364

    Args:
365 366
        x(Tensor): The input tensor, it's data type should be float32, float64..
        y(Tensor): The input tensor, it's data type should be float32, float64..
H
huangxu96 已提交
367 368
        rtol(rtoltype, optional): The relative tolerance. Default: :math:`1e-5` .
        atol(atoltype, optional): The absolute tolerance. Default: :math:`1e-8` .
369 370 371
        equal_nan(equalnantype, optional): ${equal_nan_comment}.
        name (str, optional): Name for the operation. For more information, please
            refer to :ref:`api_guide_Name`. Default: None.
Z
Zhen Wang 已提交
372 373

    Returns:
374
        Tensor: The output tensor, it's data type is bool.
375

Z
Zhen Wang 已提交
376 377 378 379 380
    Examples:
        .. code-block:: python

          import paddle

381 382
          x = paddle.to_tensor([10000., 1e-07])
          y = paddle.to_tensor([10000.1, 1e-08])
383
          result1 = paddle.allclose(x, y, rtol=1e-05, atol=1e-08,
Z
Zhen Wang 已提交
384
                                  equal_nan=False, name="ignore_nan")
385
          # [False]
386

387
          result2 = paddle.allclose(x, y, rtol=1e-05, atol=1e-08,
Z
Zhen Wang 已提交
388
                                      equal_nan=True, name="equal_nan")
389 390
          # [False]

391 392
          x = paddle.to_tensor([1.0, float('nan')])
          y = paddle.to_tensor([1.0, float('nan')])
393 394 395
          result1 = paddle.allclose(x, y, rtol=1e-05, atol=1e-08,
                                  equal_nan=False, name="ignore_nan")
          # [False]
396

397 398 399
          result2 = paddle.allclose(x, y, rtol=1e-05, atol=1e-08,
                                      equal_nan=True, name="equal_nan")
          # [True]
Z
Zhen Wang 已提交
400 401
    """

402
    if in_dygraph_mode():
403
        return _C_ops.allclose(x, y, rtol, atol, equal_nan)
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    else:
        check_variable_and_dtype(x, "input", ['float32', 'float64'], 'allclose')
        check_variable_and_dtype(y, "input", ['float32', 'float64'], 'allclose')
        check_type(rtol, 'rtol', float, 'allclose')
        check_type(atol, 'atol', float, 'allclose')
        check_type(equal_nan, 'equal_nan', bool, 'allclose')

        helper = LayerHelper("allclose", **locals())
        out = helper.create_variable_for_type_inference(dtype='bool')

        inputs = {'Input': x, 'Other': y}
        outputs = {'Out': out}
        attrs = {'rtol': str(rtol), 'atol': str(atol), 'equal_nan': equal_nan}
        helper.append_op(
            type='allclose', inputs=inputs, outputs=outputs, attrs=attrs
419
        )
Z
Zhen Wang 已提交
420

421
        return out
422 423


W
wawltor 已提交
424 425
@templatedoc()
def equal(x, y, name=None):
426
    """
S
swtkiwi 已提交
427

428
    This layer returns the truth value of :math:`x == y` elementwise.
N
Noel 已提交
429

430
    Note:
431
        The output has no gradient.
432 433

    Args:
陈沧夜 已提交
434 435
        x(Tensor): Tensor, data type is bool, float16, float32, float64, int32, int64.
        y(Tensor): Tensor, data type is bool, float16, float32, float64, int32, int64.
436 437 438 439
        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:
W
wawltor 已提交
440
        Tensor: output Tensor, it's shape is the same as the input's Tensor,
441
        and the data type is bool. The result of this op is stop_gradient.
442 443 444 445

    Examples:
        .. code-block:: python

W
wawltor 已提交
446 447
          import paddle

448 449
          x = paddle.to_tensor([1, 2, 3])
          y = paddle.to_tensor([1, 3, 2])
W
wawltor 已提交
450
          result1 = paddle.equal(x, y)
N
Noel 已提交
451
          print(result1)  # result1 = [True False False]
452
    """
453 454
    if not isinstance(y, (int, bool, float, Variable)):
        raise TypeError(
455 456 457 458
            "Type of input args must be float, bool, int or Tensor, but received type {}".format(
                type(y)
            )
        )
459
    if not isinstance(y, Variable):
460
        y = full(shape=[], dtype=x.dtype, fill_value=y)
461

J
Jiabin Yang 已提交
462
    if in_dygraph_mode():
463
        return _C_ops.equal(x, y)
J
Jiabin Yang 已提交
464
    else:
465 466 467
        check_variable_and_dtype(
            x,
            "x",
陈沧夜 已提交
468
            ["bool", "float16", "float32", "float64", "int32", "int64"],
469 470 471 472 473
            "equal",
        )
        check_variable_and_dtype(
            y,
            "y",
陈沧夜 已提交
474
            ["bool", "float16", "float32", "float64", "int32", "int64"],
475 476 477 478 479
            "equal",
        )
        helper = LayerHelper("equal", **locals())
        out = helper.create_variable_for_type_inference(dtype='bool')
        out.stop_gradient = True
J
Jiabin Yang 已提交
480

481 482 483 484 485 486
        helper.append_op(
            type='equal',
            inputs={'X': [x], 'Y': [y]},
            outputs={'Out': [out]},
        )
        return out
487

W
wawltor 已提交
488 489 490 491

@templatedoc()
def greater_equal(x, y, name=None):
    """
492
    Returns the truth value of :math:`x >= y` elementwise, which is equivalent function to the overloaded operator `>=`.
N
Noel 已提交
493

494
    Note:
495
        The output has no gradient.
W
wawltor 已提交
496 497

    Args:
498 499
        x(Tensor): First input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64.
        y(Tensor): Second input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64.
W
wawltor 已提交
500 501 502
        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:
503
        Tensor: The output shape is same as input :attr:`x`. The output data type is bool.
W
wawltor 已提交
504 505 506

    Examples:
        .. code-block:: python
N
Noel 已提交
507

W
wawltor 已提交
508 509
            import paddle

510 511
            x = paddle.to_tensor([1, 2, 3])
            y = paddle.to_tensor([1, 3, 2])
W
wawltor 已提交
512
            result1 = paddle.greater_equal(x, y)
N
Noel 已提交
513
            print(result1)  # result1 = [True False True]
W
wawltor 已提交
514
    """
J
Jiabin Yang 已提交
515
    if in_dygraph_mode():
516
        return _C_ops.greater_equal(x, y)
J
Jiabin Yang 已提交
517
    else:
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
        check_variable_and_dtype(
            x,
            "x",
            ["bool", "float32", "float64", "int32", "int64"],
            "greater_equal",
        )
        check_variable_and_dtype(
            y,
            "y",
            ["bool", "float32", "float64", "int32", "int64"],
            "greater_equal",
        )
        helper = LayerHelper("greater_equal", **locals())
        out = helper.create_variable_for_type_inference(dtype='bool')
        out.stop_gradient = True
J
Jiabin Yang 已提交
533

534 535 536 537 538 539
        helper.append_op(
            type='greater_equal',
            inputs={'X': [x], 'Y': [y]},
            outputs={'Out': [out]},
        )
        return out
W
wawltor 已提交
540 541 542 543 544


@templatedoc()
def greater_than(x, y, name=None):
    """
545
    Returns the truth value of :math:`x > y` elementwise, which is equivalent function to the overloaded operator `>`.
N
Noel 已提交
546

547
    Note:
548
        The output has no gradient.
W
wawltor 已提交
549 550

    Args:
J
Jx-qi 已提交
551 552
        x(Tensor): First input to compare which is N-D tensor. The input data type should be bool, float16, float32, float64, int32, int64.
        y(Tensor): Second input to compare which is N-D tensor. The input data type should be bool, float16, float32, float64, int32, int64.
W
wawltor 已提交
553 554 555
        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:
556
        Tensor: The output shape is same as input :attr:`x`. The output data type is bool.
W
wawltor 已提交
557 558 559

    Examples:
        .. code-block:: python
N
Noel 已提交
560

W
wawltor 已提交
561 562
            import paddle

563 564
            x = paddle.to_tensor([1, 2, 3])
            y = paddle.to_tensor([1, 3, 2])
W
wawltor 已提交
565
            result1 = paddle.greater_than(x, y)
N
Noel 已提交
566
            print(result1)  # result1 = [False False True]
W
wawltor 已提交
567
    """
J
Jiabin Yang 已提交
568
    if in_dygraph_mode():
569
        return _C_ops.greater_than(x, y)
J
Jiabin Yang 已提交
570
    else:
571 572 573
        check_variable_and_dtype(
            x,
            "x",
J
Jx-qi 已提交
574
            ["bool", "float16", "float32", "float64", "int32", "int64"],
575 576 577 578 579
            "greater_than",
        )
        check_variable_and_dtype(
            y,
            "y",
J
Jx-qi 已提交
580
            ["bool", "float16", "float32", "float64", "int32", "int64"],
581 582 583 584 585
            "greater_than",
        )
        helper = LayerHelper("greater_than", **locals())
        out = helper.create_variable_for_type_inference(dtype='bool')
        out.stop_gradient = True
J
Jiabin Yang 已提交
586

587 588 589 590 591 592
        helper.append_op(
            type='greater_than',
            inputs={'X': [x], 'Y': [y]},
            outputs={'Out': [out]},
        )
        return out
W
wawltor 已提交
593 594 595 596 597


@templatedoc()
def less_equal(x, y, name=None):
    """
598
    Returns the truth value of :math:`x <= y` elementwise, which is equivalent function to the overloaded operator `<=`.
N
Noel 已提交
599

600
    Note:
601
        The output has no gradient.
W
wawltor 已提交
602 603

    Args:
604 605
        x(Tensor): First input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64.
        y(Tensor): Second input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64.
W
wawltor 已提交
606 607 608 609
        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:
610
        Tensor: The output shape is same as input :attr:`x`. The output data type is bool.
W
wawltor 已提交
611 612 613

    Examples:
        .. code-block:: python
N
Noel 已提交
614

W
wawltor 已提交
615 616
            import paddle

617 618
            x = paddle.to_tensor([1, 2, 3])
            y = paddle.to_tensor([1, 3, 2])
W
wawltor 已提交
619
            result1 = paddle.less_equal(x, y)
N
Noel 已提交
620
            print(result1)  # result1 = [True True False]
W
wawltor 已提交
621
    """
J
Jiabin Yang 已提交
622
    if in_dygraph_mode():
623
        return _C_ops.less_equal(x, y)
J
Jiabin Yang 已提交
624
    else:
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
        check_variable_and_dtype(
            x,
            "x",
            ["bool", "float32", "float64", "int32", "int64"],
            "less_equal",
        )
        check_variable_and_dtype(
            y,
            "y",
            ["bool", "float32", "float64", "int32", "int64"],
            "less_equal",
        )
        helper = LayerHelper("less_equal", **locals())
        out = helper.create_variable_for_type_inference(dtype='bool')
        out.stop_gradient = True
J
Jiabin Yang 已提交
640

641 642 643 644 645 646
        helper.append_op(
            type='less_equal',
            inputs={'X': [x], 'Y': [y]},
            outputs={'Out': [out]},
        )
        return out
W
wawltor 已提交
647 648 649 650 651


@templatedoc()
def less_than(x, y, name=None):
    """
652
    Returns the truth value of :math:`x < y` elementwise, which is equivalent function to the overloaded operator `<`.
N
Noel 已提交
653

654
    Note:
655
        The output has no gradient.
W
wawltor 已提交
656 657

    Args:
H
hh-qiao 已提交
658 659
        x(Tensor): First input to compare which is N-D tensor. The input data type should be bool, float16, float32, float64, int32, int64.
        y(Tensor): Second input to compare which is N-D tensor. The input data type should be bool, float16, float32, float64, int32, int64.
W
wawltor 已提交
660 661 662 663
        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:
664
        Tensor: The output shape is same as input :attr:`x`. The output data type is bool.
W
wawltor 已提交
665 666 667

    Examples:
        .. code-block:: python
N
Noel 已提交
668

W
wawltor 已提交
669 670
            import paddle

671 672
            x = paddle.to_tensor([1, 2, 3])
            y = paddle.to_tensor([1, 3, 2])
W
wawltor 已提交
673
            result1 = paddle.less_than(x, y)
N
Noel 已提交
674
            print(result1)  # result1 = [False True False]
W
wawltor 已提交
675
    """
J
Jiabin Yang 已提交
676
    if in_dygraph_mode():
677
        return _C_ops.less_than(x, y)
J
Jiabin Yang 已提交
678
    else:
679 680 681
        check_variable_and_dtype(
            x,
            "x",
H
hh-qiao 已提交
682
            ["bool", "float16", "float32", "float64", "int32", "int64"],
683 684 685 686 687
            "less_than",
        )
        check_variable_and_dtype(
            y,
            "y",
H
hh-qiao 已提交
688
            ["bool", "float16", "float32", "float64", "int32", "int64"],
689 690 691 692 693
            "less_than",
        )
        helper = LayerHelper("less_than", **locals())
        out = helper.create_variable_for_type_inference(dtype='bool')
        out.stop_gradient = True
J
Jiabin Yang 已提交
694

695 696 697 698 699 700
        helper.append_op(
            type='less_than',
            inputs={'X': [x], 'Y': [y]},
            outputs={'Out': [out]},
        )
        return out
W
wawltor 已提交
701 702 703 704 705


@templatedoc()
def not_equal(x, y, name=None):
    """
706
    Returns the truth value of :math:`x != y` elementwise, which is equivalent function to the overloaded operator `!=`.
707 708

    Note:
709
        The output has no gradient.
W
wawltor 已提交
710 711

    Args:
712 713
        x(Tensor): First input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64.
        y(Tensor): Second input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64.
W
wawltor 已提交
714 715 716 717
        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:
718
        Tensor: The output shape is same as input :attr:`x`. The output data type is bool.
W
wawltor 已提交
719 720 721

    Examples:
        .. code-block:: python
722

W
wawltor 已提交
723 724
            import paddle

725 726
            x = paddle.to_tensor([1, 2, 3])
            y = paddle.to_tensor([1, 3, 2])
W
wawltor 已提交
727
            result1 = paddle.not_equal(x, y)
N
Noel 已提交
728
            print(result1)  # result1 = [False True True]
W
wawltor 已提交
729
    """
J
Jiabin Yang 已提交
730
    if in_dygraph_mode():
731
        return _C_ops.not_equal(x, y)
J
Jiabin Yang 已提交
732
    else:
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
        check_variable_and_dtype(
            x,
            "x",
            ["bool", "float32", "float64", "int32", "int64"],
            "not_equal",
        )
        check_variable_and_dtype(
            y,
            "y",
            ["bool", "float32", "float64", "int32", "int64"],
            "not_equal",
        )
        helper = LayerHelper("not_equal", **locals())
        out = helper.create_variable_for_type_inference(dtype='bool')
        out.stop_gradient = True
J
Jiabin Yang 已提交
748

749 750 751 752 753 754
        helper.append_op(
            type='not_equal',
            inputs={'X': [x], 'Y': [y]},
            outputs={'Out': [out]},
        )
        return out
Z
zhulei 已提交
755 756 757 758 759


def is_tensor(x):
    """

C
Chen Long 已提交
760
    Tests whether input object is a paddle.Tensor.
Z
zhulei 已提交
761 762 763 764 765

    Args:
        x (object): Object to test.

    Returns:
C
Chen Long 已提交
766
        A boolean value. True if ``x`` is a paddle.Tensor, otherwise False.
Z
zhulei 已提交
767 768 769 770 771 772 773 774 775 776 777 778 779

    Examples:
        .. code-block:: python

            import paddle

            input1 = paddle.rand(shape=[2, 3, 5], dtype='float32')
            check = paddle.is_tensor(input1)
            print(check)  #True

            input3 = [1, 4]
            check = paddle.is_tensor(input3)
            print(check)  #False
780

Z
zhulei 已提交
781
    """
782 783 784 785
    if in_dygraph_mode():
        return isinstance(x, (Tensor, paddle.fluid.core.eager.Tensor))
    else:
        return isinstance(x, Variable)
786 787 788


def _bitwise_op(op_name, x, y, out=None, name=None, binary_op=True):
789
    if in_dygraph_mode():
W
wanghuancoder 已提交
790
        op = getattr(_C_ops, op_name)
791 792 793 794
        if binary_op:
            return op(x, y)
        else:
            return op(x)
795
    else:
796
        check_variable_and_dtype(
797 798
            x,
            "x",
799 800 801
            ["bool", "uint8", "int8", "int16", "int32", "int64"],
            op_name,
        )
802 803 804 805 806 807 808 809 810
        if y is not None:
            check_variable_and_dtype(
                y,
                "y",
                ["bool", "uint8", "int8", "int16", "int32", "int64"],
                op_name,
            )
        if out is not None:
            check_type(out, "out", Variable, op_name)
811

812 813 814
        helper = LayerHelper(op_name, **locals())
        if binary_op:
            assert x.dtype == y.dtype
815

816 817
        if out is None:
            out = helper.create_variable_for_type_inference(dtype=x.dtype)
818

819 820 821 822 823 824 825 826
        if binary_op:
            helper.append_op(
                type=op_name, inputs={"X": x, "Y": y}, outputs={"Out": out}
            )
        else:
            helper.append_op(
                type=op_name, inputs={"X": x}, outputs={"Out": out}
            )
827

828
        return out
829 830 831


def bitwise_and(x, y, out=None, name=None):
832 833 834 835 836 837 838 839 840 841 842
    r"""

    Apply ``bitwise_and`` on Tensor ``X`` and ``Y`` .

    .. math::
        Out = X \& Y

    .. note::
        ``paddle.bitwise_and`` supports broadcasting. If you want know more about broadcasting, please refer to please refer to `Introduction to Tensor`_ .

    .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor.
843

844
    Args:
845 846 847
        x (Tensor): Input Tensor of ``bitwise_and`` . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.
        y (Tensor): Input Tensor of ``bitwise_and`` . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.
        out(Tensor): Result of ``bitwise_and`` . It is a N-D Tensor with the same data type of input Tensor.
848 849

    Returns:
850
        Tensor: Result of ``bitwise_and`` . It is a N-D Tensor with the same data type of input Tensor.
851

852 853 854 855 856 857 858 859 860
    Examples:
        .. code-block:: python

            import paddle
            x = paddle.to_tensor([-5, -1, 1])
            y = paddle.to_tensor([4,  2, -3])
            res = paddle.bitwise_and(x, y)
            print(res)  # [0, 2, 1]
    """
0
0x45f 已提交
861
    if in_dygraph_mode() and out is None:
862
        return _C_ops.bitwise_and(x, y)
863 864 865
    return _bitwise_op(
        op_name="bitwise_and", x=x, y=y, name=name, out=out, binary_op=True
    )
866 867 868


def bitwise_or(x, y, out=None, name=None):
869 870 871 872 873 874 875 876 877 878 879
    r"""

    Apply ``bitwise_or`` on Tensor ``X`` and ``Y`` .

    .. math::
        Out = X | Y

    .. note::
        ``paddle.bitwise_or`` supports broadcasting. If you want know more about broadcasting, please refer to please refer to `Introduction to Tensor`_ .

    .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor.
880

881
    Args:
882 883 884
        x (Tensor): Input Tensor of ``bitwise_or`` . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.
        y (Tensor): Input Tensor of ``bitwise_or`` . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.
        out(Tensor): Result of ``bitwise_or`` . It is a N-D Tensor with the same data type of input Tensor.
885 886

    Returns:
887
        Tensor: Result of ``bitwise_or`` . It is a N-D Tensor with the same data type of input Tensor.
888 889 890 891 892 893 894 895 896 897

    Examples:
        .. code-block:: python

            import paddle
            x = paddle.to_tensor([-5, -1, 1])
            y = paddle.to_tensor([4,  2, -3])
            res = paddle.bitwise_or(x, y)
            print(res)  # [-1, -1, -3]
    """
0
0x45f 已提交
898
    if in_dygraph_mode() and out is None:
899
        return _C_ops.bitwise_or(x, y)
H
hong 已提交
900

901 902 903
    return _bitwise_op(
        op_name="bitwise_or", x=x, y=y, name=name, out=out, binary_op=True
    )
904 905 906


def bitwise_xor(x, y, out=None, name=None):
907 908 909 910 911 912 913 914 915 916 917
    r"""

    Apply ``bitwise_xor`` on Tensor ``X`` and ``Y`` .

    .. math::
        Out = X ^\wedge Y

    .. note::
        ``paddle.bitwise_xor`` supports broadcasting. If you want know more about broadcasting, please refer to please refer to `Introduction to Tensor`_ .

    .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor.
918 919

    Args:
920 921 922
        x (Tensor): Input Tensor of ``bitwise_xor`` . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.
        y (Tensor): Input Tensor of ``bitwise_xor`` . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.
        out(Tensor): Result of ``bitwise_xor`` . It is a N-D Tensor with the same data type of input Tensor.
923 924

    Returns:
925
        Tensor: Result of ``bitwise_xor`` . It is a N-D Tensor with the same data type of input Tensor.
926 927 928 929 930 931 932 933 934 935

    Examples:
        .. code-block:: python

            import paddle
            x = paddle.to_tensor([-5, -1, 1])
            y = paddle.to_tensor([4,  2, -3])
            res = paddle.bitwise_xor(x, y)
            print(res) # [-1, -3, -4]
    """
0
0x45f 已提交
936
    if in_dygraph_mode() and out is None:
937
        return _C_ops.bitwise_xor(x, y)
938 939 940
    return _bitwise_op(
        op_name="bitwise_xor", x=x, y=y, name=name, out=out, binary_op=True
    )
941 942 943


def bitwise_not(x, out=None, name=None):
944 945 946 947 948 949 950 951 952 953 954
    r"""

    Apply ``bitwise_not`` on Tensor ``X``.

    .. math::
        Out = \sim X

    .. note::
        ``paddle.bitwise_not`` supports broadcasting. If you want know more about broadcasting, please refer to please refer to `Introduction to Tensor`_ .

        .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor.
955 956

    Args:
957 958
        x (Tensor): Input Tensor of ``bitwise_not`` . It is a N-D Tensor of bool, uint8, int8, int16, int32, int64.
        out(Tensor): Result of ``bitwise_not`` . It is a N-D Tensor with the same data type of input Tensor.
959

960
    Returns:
961
        Tensor: Result of ``bitwise_not`` . It is a N-D Tensor with the same data type of input Tensor.
962 963 964 965 966 967 968 969 970

    Examples:
        .. code-block:: python

            import paddle
            x = paddle.to_tensor([-5, -1, 1])
            res = paddle.bitwise_not(x)
            print(res) # [4, 0, -2]
    """
0
0x45f 已提交
971
    if in_dygraph_mode() and out is None:
972
        return _C_ops.bitwise_not(x)
973

974 975 976
    return _bitwise_op(
        op_name="bitwise_not", x=x, y=None, name=name, out=out, binary_op=False
    )
A
andyjpaddle 已提交
977 978 979 980


@templatedoc()
def isclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name=None):
981
    r"""
982
    Check if all :math:`x` and :math:`y` satisfy the condition:
983 984 985 986 987 988 989 990

    .. math::

        \left| x - y \right| \leq atol + rtol \times \left| y \right|

    elementwise, for all elements of :math:`x` and :math:`y`. The behaviour of this
    operator is analogous to :math:`numpy.isclose`, namely that it returns :math:`True` if
    two tensors are elementwise equal within a tolerance.
A
andyjpaddle 已提交
991 992

    Args:
993 994
        x(Tensor): The input tensor, it's data type should be float32, float64.
        y(Tensor): The input tensor, it's data type should be float32, float64.
A
andyjpaddle 已提交
995 996
        rtol(rtoltype, optional): The relative tolerance. Default: :math:`1e-5` .
        atol(atoltype, optional): The absolute tolerance. Default: :math:`1e-8` .
997
        equal_nan(equalnantype, optional): If :math:`True` , then two :math:`NaNs` will be compared as equal. Default: :math:`False` .
A
andyjpaddle 已提交
998 999 1000 1001
        name (str, optional): Name for the operation. For more information, please
            refer to :ref:`api_guide_Name`. Default: None.

    Returns:
1002
        Tensor: The output tensor, it's data type is bool.
A
andyjpaddle 已提交
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027

    Examples:
        .. code-block:: python

          import paddle

          x = paddle.to_tensor([10000., 1e-07])
          y = paddle.to_tensor([10000.1, 1e-08])
          result1 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08,
                                  equal_nan=False, name="ignore_nan")
          # [True, False]
          result2 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08,
                                      equal_nan=True, name="equal_nan")
          # [True, False]

          x = paddle.to_tensor([1.0, float('nan')])
          y = paddle.to_tensor([1.0, float('nan')])
          result1 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08,
                                  equal_nan=False, name="ignore_nan")
          # [True, False]
          result2 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08,
                                      equal_nan=True, name="equal_nan")
          # [True, True]
    """

1028
    if in_dygraph_mode():
1029
        return _C_ops.isclose(x, y, rtol, atol, equal_nan)
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    else:
        check_variable_and_dtype(x, "input", ['float32', 'float64'], 'isclose')
        check_variable_and_dtype(y, "input", ['float32', 'float64'], 'isclose')
        check_type(rtol, 'rtol', float, 'isclose')
        check_type(atol, 'atol', float, 'isclose')
        check_type(equal_nan, 'equal_nan', bool, 'isclose')

        helper = LayerHelper("isclose", **locals())
        out = helper.create_variable_for_type_inference(dtype='bool')

        inputs = {'Input': x, 'Other': y}
        outputs = {'Out': out}
        attrs = {'rtol': str(rtol), 'atol': str(atol), 'equal_nan': equal_nan}
        helper.append_op(
            type='isclose', inputs=inputs, outputs=outputs, attrs=attrs
1045
        )
1046
        return out