refine docs of rand, randn, randint, randperm, zeros_like, arange (#25633)

fix_copy_if_different
zhupengyang 5 years ago committed by GitHub
parent 2469b578f5
commit 0ca1bb56df
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -10427,47 +10427,58 @@ def gaussian_random(shape,
dtype='float32', dtype='float32',
name=None): name=None):
""" """
Generate a random tensor whose data is drawn from a Gaussian distribution. This OP returns a Tensor filled with random values sampled from a Gaussian
distribution, with ``shape`` and ``dtype``.
Args: Args:
shape(list|tuple|Variable): Shape of the Tensor to be created. The data shape(list|tuple|Tensor): The shape of the output Tensor. If ``shape``
type is ``int32`` or ``int64`` . If ``shape`` is a list or tuple, is a list or tuple, the elements of it should be integers or Tensors
the elements of it should be integers or Tensors with shape [1]. If (with the shape [1], and the data type int32 or int64). If ``shape``
``shape`` is a Variable, it should be an 1-D Tensor . is a Tensor, it should be a 1-D Tensor(with the data type int32 or
mean(float): Mean of the random tensor, defaults to 0.0. int64).
std(float): Standard deviation of the random tensor, defaults to 1.0. mean(float|int, optional): Mean of the output tensor, default is 0.0.
seed(int): ${seed_comment} std(float|int, optional): Standard deviation of the output tensor, default
dtype(np.dtype|core.VarDesc.VarType|str, optional): Data type of the output is 1.0.
tensor, which can be float32, float64. Default is float32. seed(int, optional): ${seed_comment}
name(str, optional): Normally there is no need for user to set this property. dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of
For more information, please refer to :ref:`api_guide_Name` . the output Tensor. Supported data types: float32, float64.
Default is None. Default is float32.
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: Random tensor whose data is drawn from a Gaussian distribution, dtype: flaot32 or float64 as specified. Tensor: A Tensor filled with random values sampled from a Gaussian
distribution, with ``shape`` and ``dtype``.
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle.fluid as fluid import paddle.fluid as fluid
# example 1: # example 1:
# attr shape is a list which doesn't contain tensor Variable. # attr shape is a list which doesn't contain Tensor.
result_1 = fluid.layers.gaussian_random(shape=[3, 4]) result_1 = fluid.layers.gaussian_random(shape=[3, 4])
# [[-0.31261674, 1.8736548, -0.6274357, 0.96988016],
# [-0.12294637, 0.9554768, 1.5690808, -1.2894802 ],
# [-0.60082096, -0.61138713, 1.5345167, -0.21834975]]
# example 2: # example 2:
# attr shape is a list which contains tensor Variable. # attr shape is a list which contains Tensor.
dim_1 = fluid.layers.fill_constant([1],"int64",3) dim_1 = fluid.layers.fill_constant([1], "int64", 2)
dim_2 = fluid.layers.fill_constant([1],"int32",5) dim_2 = fluid.layers.fill_constant([1], "int32", 3)
result_2 = fluid.layers.gaussian_random(shape=[dim_1, dim_2]) result_2 = fluid.layers.gaussian_random(shape=[dim_1, dim_2])
# [[ 0.51398206, -0.3389769, 0.23597084],
# [ 1.0388143, -1.2015356, -1.0499583 ]]
# example 3: # example 3:
# attr shape is a Variable, the data type must be int64 or int32. # attr shape is a Tensor, the data type must be int64 or int32.
var_shape = fluid.data(name='var_shape', shape=[2], dtype="int64") var_shape = fluid.data(name='var_shape', shape=[2], dtype="int64")
result_3 = fluid.layers.gaussian_random(var_shape) result_3 = fluid.layers.gaussian_random(var_shape)
var_shape_int32 = fluid.data(name='var_shape_int32', shape=[2], dtype="int32") # if var_shape's value is [2, 3]
result_4 = fluid.layers.gaussian_random(var_shape_int32) # result_3 is:
# [[-0.12310527, 0.8187662, 1.923219 ]
# [ 0.70721835, 0.5210541, -0.03214082]]
.. code-block:: python .. code-block:: python
@ -10509,8 +10520,10 @@ def gaussian_random(shape,
if in_dygraph_mode(): if in_dygraph_mode():
shape = utils._convert_shape_to_list(shape) shape = utils._convert_shape_to_list(shape)
return core.ops.gaussian_random('shape', shape, 'mean', mean, 'std', return core.ops.gaussian_random('shape', shape, 'mean',
std, 'seed', seed, 'dtype', dtype) float(mean), 'std',
float(std), 'seed', seed, 'dtype',
dtype)
check_type(shape, 'shape', (list, tuple, Variable), 'gaussian_random/randn') check_type(shape, 'shape', (list, tuple, Variable), 'gaussian_random/randn')
check_dtype(dtype, 'dtype', ['float32', 'float64'], 'gaussian_random/randn') check_dtype(dtype, 'dtype', ['float32', 'float64'], 'gaussian_random/randn')
@ -14917,8 +14930,8 @@ def gather_tree(ids, parents):
def uniform_random(shape, dtype='float32', min=-1.0, max=1.0, seed=0, def uniform_random(shape, dtype='float32', min=-1.0, max=1.0, seed=0,
name=None): name=None):
""" """
This OP initializes a variable with random values sampled from a This OP returns a Tensor filled with random values sampled from a uniform
uniform distribution in the range [min, max). distribution in the range [``min``, ``max``), with ``shape`` and ``dtype``.
Examples: Examples:
:: ::
@ -14930,30 +14943,33 @@ def uniform_random(shape, dtype='float32', min=-1.0, max=1.0, seed=0,
result=[[0.8505902, 0.8397286]] result=[[0.8505902, 0.8397286]]
Args: Args:
shape (list|tuple|Variable): The shape of the output Tensor, if the shape(list|tuple|Tensor): The shape of the output Tensor. If ``shape``
shape is a list or tuple, its elements can be an integer or a is a list or tuple, the elements of it should be integers or Tensors
Tensor with the shape [1], and the type of the Tensor must be (with the shape [1], and the data type int32 or int64). If ``shape``
int32 or int64. If the shape is a Variable, it is a 1-D Tensor, and is a Tensor, it should be a 1-D Tensor(with the data type int32 or
the type of the Tensor must be int32 or int64. int64).
dtype(np.dtype|core.VarDesc.VarType|str, optional): The type of the dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of
output Tensor. Supported data types: float32, float64. Default: float32. the output Tensor. Supported data types: float32, float64.
min (float, optional): The lower bound on the range of random values Default is float32.
to generate, the min is included in the range. Default -1.0. min(float|int, optional): The lower bound on the range of random values
max (float, optional): The upper bound on the range of random values to generate, ``min`` is included in the range. Default is -1.0.
to generate, the max is excluded in the range. Default 1.0. max(float|int, optional): The upper bound on the range of random values
seed (int, optional): Random seed used for generating samples. 0 means to generate, ``max`` is excluded in the range. Default is 1.0.
seed(int, optional): Random seed used for generating samples. 0 means
use a seed generated by the system. Note that if seed is not 0, use a seed generated by the system. Note that if seed is not 0,
this operator will always generate the same random numbers every this operator will always generate the same random numbers every
time. Default 0. time. Default is 0.
name(str, optional): The default value is None. Normally there is no name(str, optional): The default value is None. Normally there is no
need for user to set this property. For more information, please need for user to set this property. For more information, please
refer to :ref:`api_guide_Name`. refer to :ref:`api_guide_Name`.
Returns: Returns:
Variable: A Tensor of the specified shape filled with uniform_random values. Tensor: A Tensor filled with random values sampled from a uniform
distribution in the range [``min``, ``max``), with ``shape`` and ``dtype``.
Raises: Raises:
TypeError: The shape type should be list or tuple or variable. TypeError: If ``shape`` is not list, tuple, Tensor.
TypeError: If ``dtype`` is not float32, float64.
Examples: Examples:
.. code-block:: python .. code-block:: python
@ -14961,21 +14977,28 @@ def uniform_random(shape, dtype='float32', min=-1.0, max=1.0, seed=0,
import paddle.fluid as fluid import paddle.fluid as fluid
# example 1: # example 1:
# attr shape is a list which doesn't contain tensor Variable. # attr shape is a list which doesn't contain Tensor.
result_1 = fluid.layers.uniform_random(shape=[3, 4]) result_1 = fluid.layers.uniform_random(shape=[3, 4])
# [[ 0.84524226, 0.6921872, 0.56528175, 0.71690357],
# [-0.34646994, -0.45116323, -0.09902662, -0.11397249],
# [ 0.433519, 0.39483607, -0.8660099, 0.83664286]]
# example 2: # example 2:
# attr shape is a list which contains tensor Variable. # attr shape is a list which contains Tensor.
dim_1 = fluid.layers.fill_constant([1],"int64",3) dim_1 = fluid.layers.fill_constant([1], "int64", 2)
dim_2 = fluid.layers.fill_constant([1],"int32",5) dim_2 = fluid.layers.fill_constant([1], "int32", 3)
result_2 = fluid.layers.uniform_random(shape=[dim_1, dim_2]) result_2 = fluid.layers.uniform_random(shape=[dim_1, dim_2])
# [[-0.9951253, 0.30757582, 0.9899647 ],
# [ 0.5864527, 0.6607096, -0.8886161 ]]
# example 3: # example 3:
# attr shape is a Variable, the data type must be int64 or int32. # attr shape is a Tensor, the data type must be int64 or int32.
var_shape = fluid.data(name='var_shape', shape=[2], dtype="int64") var_shape = fluid.data(name='var_shape', shape=[2], dtype="int64")
result_3 = fluid.layers.uniform_random(var_shape) result_3 = fluid.layers.uniform_random(var_shape)
var_shape_int32 = fluid.data(name='var_shape_int32', shape=[2], dtype="int32") # if var_shape's value is [2, 3]
result_4 = fluid.layers.uniform_random(var_shape_int32) # result_3 is:
# [[-0.8517412, -0.4006908, 0.2551912 ],
# [ 0.3364414, 0.36278176, -0.16085452]]
""" """
if not isinstance(dtype, core.VarDesc.VarType): if not isinstance(dtype, core.VarDesc.VarType):

@ -1335,35 +1335,38 @@ def isfinite(x):
def range(start, end, step, dtype, name=None): def range(start, end, step, dtype, name=None):
""" """
Return evenly spaced values within a given interval. This OP returns a 1-D Tensor with spaced values within a given interval.
Values are generated within the half-open interval [start, stop) (in other Values are generated into the half-open interval [``start``, ``end``) with
words, the interval including start but excluding stop). the ``step``. (the interval including ``start`` but excluding ``end``).
If dtype is float32 or float64, we advise adding a small epsilon to end to If ``dtype`` is float32 or float64, we advise adding a small epsilon to
avoid floating point rounding errors when comparing against end. ``end`` to avoid floating point rounding errors when comparing against ``end``.
Parameters: Parameters:
start(float|int|Variable): Start of interval. The interval includes start(float|int|Tensor): Start of interval. The interval includes this
this value. If start is Variable, it is a 1-D Tensor with shape [1], value. If ``start`` is a Tensor, it is a 1-D Tensor with shape [1],
and it's data type should be one of int32, int64, float32, float64. with data type int32, int64, float32, float64.
end(float|int|Variable): End of interval. The interval does not include end(float|int|Tensor): End of interval. The interval does not include
this value. When end is Variable, it is a 1-D Tensor with shape [1], this value. If ``end`` is a Tensor, it is a 1-D Tensor with shape
and it's data type should be int32, int64, float32, float64. [1], with data type int32, int64, float32, float64.
step(float|int|Variable): Spacing between values. For any out, this is step(float|int|Tensor): Spacing between values. For any out, it is
the istance between two adjacent values, out[i+1] - out[i]. the istance between two adjacent values, out[i+1] - out[i]. If
When end is Variable, it is a 1-D Tensor with shape [1], and it's ``step`` is a Tensor, it is a 1-D Tensor with shape [1], with data
data type should be one of int32, int64, float32, float64. type int32, int64, float32, float64.
dtype(str|np.dtype|core.VarDesc.VarType): The data type of the output dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of the
tensor, can be float32, float64, int32, int64. output tensor. Supported data types: int32, int64, float32, float64.
name(str, optional): Normally there is no need for user to set this property. name(str, optional): The default value is None. Normally there is no
For more information, please refer to :ref:`api_guide_Name` . need for user to set this property. For more information, please
Default is None. refer to :ref:`api_guide_Name`.
Returns: a 1-D Tensor which is evenly spaced values within a given interval. Returns:
Its data type is set by dtype. Tensor: A 1-D Tensor with values from the interval [``start``, ``end``)
taken with common difference ``step`` beginning from ``start``. Its
Return type: Variable data type is set by ``dtype``.
Raises:
TypeError: If ``dtype`` is not int32, int64, float32, float64.
examples: examples:

@ -27,18 +27,23 @@ from op_test import OpTest
class TestGaussianRandomOp(OpTest): class TestGaussianRandomOp(OpTest):
def setUp(self): def setUp(self):
self.op_type = "gaussian_random" self.op_type = "gaussian_random"
self.set_attrs()
self.inputs = {} self.inputs = {}
self.use_mkldnn = False self.use_mkldnn = False
self.attrs = { self.attrs = {
"shape": [123, 92], "shape": [123, 92],
"mean": 1.0, "mean": self.mean,
"std": 2., "std": self.std,
"seed": 10, "seed": 10,
"use_mkldnn": self.use_mkldnn "use_mkldnn": self.use_mkldnn
} }
self.outputs = {'Out': np.zeros((123, 92), dtype='float32')} self.outputs = {'Out': np.zeros((123, 92), dtype='float32')}
def set_attrs(self):
self.mean = 1.0
self.std = 2.
def test_check_output(self): def test_check_output(self):
self.check_output_customized(self.verify_output) self.check_output_customized(self.verify_output)
@ -57,6 +62,12 @@ class TestGaussianRandomOp(OpTest):
"hist: " + str(hist) + " hist2: " + str(hist2)) "hist: " + str(hist) + " hist2: " + str(hist2))
class TestMeanStdAreInt(TestGaussianRandomOp):
def set_attrs(self):
self.mean = 1
self.std = 2
# Situation 2: Attr(shape) is a list(with tensor) # Situation 2: Attr(shape) is a list(with tensor)
class TestGaussianRandomOp_ShapeTensorList(TestGaussianRandomOp): class TestGaussianRandomOp_ShapeTensorList(TestGaussianRandomOp):
def setUp(self): def setUp(self):

@ -28,11 +28,11 @@ import numpy as np
class ApiOnesTest(unittest.TestCase): class ApiOnesTest(unittest.TestCase):
def test_paddle_ones(self): def test_paddle_ones(self):
with paddle.program_guard(paddle.Program()): with paddle.program_guard(paddle.Program()):
ones = paddle.ones(shape=[10], dtype="float64") ones = paddle.ones(shape=[10])
place = paddle.CPUPlace() place = paddle.CPUPlace()
exe = paddle.Executor(place) exe = paddle.Executor(place)
result, = exe.run(fetch_list=[ones]) result, = exe.run(fetch_list=[ones])
expected_result = np.ones(10, dtype="float64") expected_result = np.ones(10, dtype="float32")
self.assertEqual((result == expected_result).all(), True) self.assertEqual((result == expected_result).all(), True)
with paddle.program_guard(paddle.Program()): with paddle.program_guard(paddle.Program()):

@ -70,6 +70,12 @@ class TestUniformRandomOp_attr_tensorlist(OpTest):
hist, prob, rtol=0, atol=0.01), "hist: " + str(hist)) hist, prob, rtol=0, atol=0.01), "hist: " + str(hist))
class TestMaxMinAreInt(TestUniformRandomOp_attr_tensorlist):
def init_attrs(self):
self.attrs = {"min": -5, "max": 10, "seed": 10}
self.output_hist = output_hist
class TestUniformRandomOp_attr_tensorlist_int32(OpTest): class TestUniformRandomOp_attr_tensorlist_int32(OpTest):
def setUp(self): def setUp(self):
self.op_type = "uniform_random" self.op_type = "uniform_random"

@ -241,26 +241,29 @@ def zeros(shape, dtype=None, name=None):
def zeros_like(x, dtype=None, name=None): def zeros_like(x, dtype=None, name=None):
""" """
:alias_main: paddle.zeros_like :alias_main: paddle.zeros_like
:alias: paddle.zeros_like, paddle.tensor.zeros_like, paddle.tensor.creation.zeros_like :alias: paddle.tensor.zeros_like, paddle.tensor.creation.zeros_like
This function creates a zeros tensor which has identical shape and dtype This OP returns a Tensor filled with the value 0, with the same shape and
with `input`. data type (use ``dtype`` if ``dtype`` is not None) as ``x``.
Args: Args:
x(Variable): The input tensor which specifies shape and dtype. The x(Tensor): The input tensor which specifies shape and dtype. The
dtype of input can be bool, float16, float32, float64, int32, int64. dtype of ``x`` can be bool, float16, float32, float64, int32, int64.
dtype(np.dtype|core.VarDesc.VarType|str, optional): The data type can dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of the
be set bool, float16, float32, float64, int32, int64. The default output tensor. Supported data types: bool, float16, float32, float64,
value is None, the dtype is the same as input. int32, int64. If ``dtype`` is None, the data type is the same as ``x``.
Default is None.
name(str, optional): The default value is None. Normally there is no name(str, optional): The default value is None. Normally there is no
need for user to set this property. For more information, please need for user to set this property. For more information, please
refer to :ref:`api_guide_Name`. refer to :ref:`api_guide_Name`.
Returns: Returns:
out(Variable): The tensor variable storing the output. Tensor: A Tensor filled with the value 0, with the same shape and
data type (use ``dtype`` if ``dtype`` is not None) as ``x``.
Raise: Raise:
TypeError: If dtype is not bool, float16, float32, float64, int32 or int64. TypeError: If ``dtype`` is not None and is not bool, float16, float32,
float64, int32 or int64.
Examples: Examples:
.. code-block:: python .. code-block:: python
@ -271,8 +274,8 @@ def zeros_like(x, dtype=None, name=None):
paddle.enable_imperative() paddle.enable_imperative()
x = paddle.imperative.to_variable(np.array([1,2,3], dtype='float32')) x = paddle.imperative.to_variable(np.array([1,2,3], dtype='float32'))
out1 = paddle.zeros_like(x) # [1.0, 1.0, 1.0] out1 = paddle.zeros_like(x) # [0., 0., 0.]
out2 = paddle.zeros_like(x, dtype='int32') # [1, 1, 1] out2 = paddle.zeros_like(x, dtype='int32') # [0, 0, 0]
""" """
return full_like(x=x, fill_value=0, dtype=dtype, name=name) return full_like(x=x, fill_value=0, dtype=dtype, name=name)
@ -388,45 +391,43 @@ def full(shape, fill_value, dtype=None, name=None):
def arange(start=0, end=None, step=1, dtype=None, name=None): def arange(start=0, end=None, step=1, dtype=None, name=None):
""" """
:alias_main: paddle.arange :alias_main: paddle.arange
:alias: paddle.arange,paddle.tensor.arange,paddle.tensor.creation.arange :alias: paddle.tensor.arange, paddle.tensor.creation.arange
Return evenly spaced values within a given interval. This OP returns a 1-D Tensor with spaced values within a given interval.
Values are generated into the half-open interval [start, stop) with the step. Values are generated into the half-open interval [``start``, ``end``) with
(the interval including start but excluding stop). the ``step``. (the interval including ``start`` but excluding ``end``).
If dtype is float32 or float64, we advise adding a small epsilon to end to If ``dtype`` is float32 or float64, we advise adding a small epsilon to
avoid floating point rounding errors when comparing against end. ``end`` to avoid floating point rounding errors when comparing against ``end``.
Parameters: Parameters:
start(float|int|Variable): Start of interval. The interval includes start(float|int|Tensor): Start of interval. The interval includes this
this value. If end is None, the half-open interval is [0, start). value. If ``end`` is None, the half-open interval is [0, ``start``).
If start is Variable, it is a 1-D Tensor with shape [1], and it's If ``start`` is a Tensor, it is a 1-D Tensor with shape [1], with
data type should be one of int32, int64, float32, float64. Default data type int32, int64, float32, float64. Default is 0.
is 0. end(float|int|Tensor, optional): End of interval. The interval does not
end(float|int|Variable, optional): End of interval. The interval does include this value. If ``end`` is a Tensor, it is a 1-D Tensor with
not include this value. When end is Variable, it is a 1-D Tensor shape [1], with data type int32, int64, float32, float64. If ``end``
with shape [1], and it's data type should be one of int32, int64, is None, the half-open interval is [0, ``start``). Default is None.
float32, float64. If end is None, the half-open interval is [0, start). step(float|int|Tensor, optional): Spacing between values. For any out,
Default is None. it is the istance between two adjacent values, out[i+1] - out[i].
step(float|int|Variable, optional): Spacing between values. For any If ``step`` is a Tensor, it is a 1-D Tensor with shape [1], with
out, this is the istance between two adjacent values, out[i+1] - out[i]. data type int32, int64, float32, float64. Default is 1.
When end is Variable, it is a 1-D Tensor with shape [1], and it's dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of the
data type should be one of int32, int64, float32, float64. Default is 1. output tensor. Supported data types: int32, int64, float32, float64.
dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of If ``dytpe`` is None, the data type is float32. Default is None.
the output tensor, can be float32, float64, int32, int64. If dtype name(str, optional): The default value is None. Normally there is no
is `None` , the data type of out tensor is `int64` . Defaule is None need for user to set this property. For more information, please
name(str, optional): Normally there is no need for user to set this property. refer to :ref:`api_guide_Name`.
For more information, please refer to :ref:`api_guide_Name` .
Default is None.
Returns: a 1-D Tensor which is evenly spaced values within a given interval. Returns:
Its data type is set by dtype. Tensor: A 1-D Tensor with values from the interval [``start``, ``end``)
taken with common difference ``step`` beginning from ``start``. Its
Return type: Variable data type is set by ``dtype``.
Raises: Raises:
TypeError: If dtype is not float32, float64, int32 or int64. TypeError: If ``dtype`` is not int32, int64, float32, float64.
examples: examples:

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save