attribute.py 10.4 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
# TODO: define functions to get tensor attributes
16

17
import numpy as np
18

19
import paddle
20
from paddle import _C_ops
21

22
from ..common_ops_import import Variable
23
from ..fluid.data_feeder import check_type, check_variable_and_dtype
24
from ..fluid.framework import in_dygraph_mode
25 26
from ..framework import LayerHelper, core
from .creation import _complex_to_real_dtype, assign
27

28 29
__all__ = []

30

31 32 33
def rank(input):
    """

C
Chen Long 已提交
34
    Returns the number of dimensions for a tensor, which is a 0-D int32 Tensor.
35 36

    Args:
C
Chen Long 已提交
37
        input (Tensor): The input Tensor with shape of :math:`[N_1, N_2, ..., N_k]`, the data type is arbitrary.
38 39 40 41 42 43 44

    Returns:
        Tensor, the output data type is int32.: The 0-D tensor with the dimensions of the input Tensor.

    Examples:
        .. code-block:: python

45
            >>> import paddle
46

47 48 49 50
            >>> input = paddle.rand((3, 100, 100))
            >>> rank = paddle.rank(input)
            >>> print(rank.numpy())
            3
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    """
    check_type(input, 'input', (Variable), 'input')
    ndims = len(input.shape)
    out = assign(np.array(ndims, 'int32'))

    return out


def shape(input):
    """
    Get the shape of the input.

    .. code-block:: text

        Case1:
            Given N-D Tensor:
                input = [ [1, 2, 3, 4], [5, 6, 7, 8] ]

            Then:
                input.shape = [2, 4]

        Case2:
            Given SelectedRows:
                input.rows = [0, 4, 19]
                input.height = 20
                input.value = [ [1, 2], [3, 4], [5, 6] ]  # inner tensor
            Then:
                input.shape = [3, 2]

    Args:
81
        input (Variable): The input can be N-D Tensor or SelectedRows with data type bool, bfloat16, float16, float32, float64, int32, int64.
82 83 84 85 86 87 88 89
                          If input variable is type of SelectedRows, returns the shape of it's inner tensor.

    Returns:
        Variable (Tensor): The shape of the input variable.

    Examples:
        .. code-block:: python

90 91 92
            >>> import numpy as np
            >>> import paddle
            >>> paddle.enable_static()
93

94 95
            >>> inputs = paddle.static.data(name="x", shape=[3, 100, 100], dtype="float32")
            >>> output = paddle.shape(inputs)
96

97 98
            >>> exe = paddle.static.Executor(paddle.CPUPlace())
            >>> exe.run(paddle.static.default_startup_program())
99

100
            >>> img = np.ones((3, 100, 100)).astype(np.float32)
101

102 103 104
            >>> res = exe.run(paddle.static.default_main_program(), feed={'x':img}, fetch_list=[output])
            >>> print(res)
            [array([  3, 100, 100], dtype=int32)]
105 106
    """
    if in_dygraph_mode():
107
        out = _C_ops.shape(input)
108 109
        out.stop_gradient = True
        return out
110 111 112 113 114 115
    else:
        check_variable_and_dtype(
            input,
            'input',
            [
                'bool',
116
                'uint16',
117 118 119 120 121 122 123
                'float16',
                'float32',
                'float64',
                'int32',
                'int64',
                'complex64',
                'complex128',
124
                'uint16',
125 126 127 128 129 130 131 132 133 134 135
            ],
            'shape',
        )
        helper = LayerHelper('shape', **locals())
        out = helper.create_variable_for_type_inference(dtype='int32')
        helper.append_op(
            type='shape',
            inputs={'Input': input},
            outputs={'Out': out},
            stop_gradient=True,
        )
X
xiongkun 已提交
136
        out.stop_gradient = True
137
        return out
138 139 140


def is_complex(x):
141 142 143 144 145 146 147 148 149 150 151
    """Return whether x is a tensor of complex data type(complex64 or complex128).

    Args:
        x (Tensor): The input tensor.

    Returns:
        bool: True if the data type of the input is complex data type, otherwise false.

    Examples:
        .. code-block:: python

152
            >>> import paddle
153

154 155 156
            >>> x = paddle.to_tensor([1 + 2j, 3 + 4j])
            >>> print(paddle.is_complex(x))
            True
157

158 159 160
            >>> x = paddle.to_tensor([1.1, 1.2])
            >>> print(paddle.is_complex(x))
            False
161

162 163 164
            >>> x = paddle.to_tensor([1, 2, 3])
            >>> print(paddle.is_complex(x))
            False
165 166
    """
    if not isinstance(x, (paddle.Tensor, paddle.static.Variable)):
167
        raise TypeError(f"Expected Tensor, but received type of x: {type(x)}")
168
    dtype = x.dtype
169 170 171 172
    is_complex_dtype = (
        dtype == core.VarDesc.VarType.COMPLEX64
        or dtype == core.VarDesc.VarType.COMPLEX128
    )
173 174 175 176
    return is_complex_dtype


def is_floating_point(x):
W
wuhuanzhou 已提交
177 178 179 180 181 182 183 184 185 186 187 188
    """
    Returns whether the dtype of `x` is one of paddle.float64, paddle.float32, paddle.float16, and paddle.bfloat16.

    Args:
        x (Tensor): The input tensor.

    Returns:
        bool: True if the dtype of `x` is floating type, otherwise false.

    Examples:
        .. code-block:: python

189
            >>> import paddle
W
wuhuanzhou 已提交
190

191 192 193 194 195 196
            >>> x = paddle.arange(1., 5., dtype='float32')
            >>> y = paddle.arange(1, 5, dtype='int32')
            >>> print(paddle.is_floating_point(x))
            True
            >>> print(paddle.is_floating_point(y))
            False
W
wuhuanzhou 已提交
197 198
    """
    if not isinstance(x, (paddle.Tensor, paddle.static.Variable)):
199
        raise TypeError(f"Expected Tensor, but received type of x: {type(x)}")
200
    dtype = x.dtype
201 202 203 204 205 206
    is_fp_dtype = (
        dtype == core.VarDesc.VarType.FP32
        or dtype == core.VarDesc.VarType.FP64
        or dtype == core.VarDesc.VarType.FP16
        or dtype == core.VarDesc.VarType.BF16
    )
207 208 209
    return is_fp_dtype


210
def is_integer(x):
211 212 213 214 215 216 217 218 219 220 221
    """Return whether x is a tensor of integeral data type.

    Args:
        x (Tensor): The input tensor.

    Returns:
        bool: True if the data type of the input is integer data type, otherwise false.

    Examples:
        .. code-block:: python

222
            >>> import paddle
223

224 225 226
            >>> x = paddle.to_tensor([1 + 2j, 3 + 4j])
            >>> print(paddle.is_integer(x))
            False
227

228 229 230
            >>> x = paddle.to_tensor([1.1, 1.2])
            >>> print(paddle.is_integer(x))
            False
231

232 233 234
            >>> x = paddle.to_tensor([1, 2, 3])
            >>> print(paddle.is_integer(x))
            True
235 236
    """
    if not isinstance(x, (paddle.Tensor, paddle.static.Variable)):
237
        raise TypeError(f"Expected Tensor, but received type of x: {type(x)}")
238
    dtype = x.dtype
239 240 241 242 243 244 245
    is_int_dtype = (
        dtype == core.VarDesc.VarType.UINT8
        or dtype == core.VarDesc.VarType.INT8
        or dtype == core.VarDesc.VarType.INT16
        or dtype == core.VarDesc.VarType.INT32
        or dtype == core.VarDesc.VarType.INT64
    )
246 247 248
    return is_int_dtype


249 250
def real(x, name=None):
    """
C
Chen Long 已提交
251
    Returns a new Tensor containing real values of the input Tensor.
252 253

    Args:
C
Chen Long 已提交
254
        x (Tensor): the input Tensor, its data type could be complex64 or complex128.
255 256
        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` .
257

258
    Returns:
C
Chen Long 已提交
259
        Tensor: a Tensor containing real values of the input Tensor.
260 261 262 263

    Examples:
        .. code-block:: python

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
            >>> import paddle

            >>> x = paddle.to_tensor(
            ...     [[1 + 6j, 2 + 5j, 3 + 4j], [4 + 3j, 5 + 2j, 6 + 1j]])
            >>> print(x)
            Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
            [[(1+6j), (2+5j), (3+4j)],
             [(4+3j), (5+2j), (6+1j)]])

            >>> real_res = paddle.real(x)
            >>> print(real_res)
            Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[1., 2., 3.],
             [4., 5., 6.]])

            >>> real_t = x.real()
            >>> print(real_t)
            Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[1., 2., 3.],
             [4., 5., 6.]])
284
    """
Z
zyfncg 已提交
285
    if in_dygraph_mode():
W
wanghuancoder 已提交
286
        return _C_ops.real(x)
287 288 289 290 291 292 293 294
    else:
        check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], 'real')
        helper = LayerHelper('real', **locals())
        out = helper.create_variable_for_type_inference(
            dtype=_complex_to_real_dtype(helper.input_dtype())
        )
        helper.append_op(type='real', inputs={'X': x}, outputs={'Out': out})
        return out
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311


def imag(x, name=None):
    """
    Returns a new tensor containing imaginary values of input tensor.

    Args:
        x (Tensor): the input tensor, its data type could be complex64 or complex128.
        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:
        Tensor: a tensor containing imaginary values of the input tensor.

    Examples:
        .. code-block:: python

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
            >>> import paddle

            >>> x = paddle.to_tensor(
            ...     [[1 + 6j, 2 + 5j, 3 + 4j], [4 + 3j, 5 + 2j, 6 + 1j]])
            >>> print(x)
            Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
            [[(1+6j), (2+5j), (3+4j)],
             [(4+3j), (5+2j), (6+1j)]])

            >>> imag_res = paddle.imag(x)
            >>> print(imag_res)
            Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[6., 5., 4.],
             [3., 2., 1.]])

            >>> imag_t = x.imag()
            >>> print(imag_t)
            Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[6., 5., 4.],
             [3., 2., 1.]])
332
    """
Z
zyfncg 已提交
333
    if in_dygraph_mode():
W
wanghuancoder 已提交
334
        return _C_ops.imag(x)
335 336 337 338 339 340 341 342
    else:
        check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], 'imag')
        helper = LayerHelper('imag', **locals())
        out = helper.create_variable_for_type_inference(
            dtype=_complex_to_real_dtype(helper.input_dtype())
        )
        helper.append_op(type='imag', inputs={'X': x}, outputs={'Out': out})
        return out