rand_like

paddle. rand_like ( input, name: str | None = None, *, dtype: DTypeLike | None = None, device: PlaceLike | None = None, requires_grad: bool = False ) [source]

Returns a tensor with the same size as input that is filled with random numbers from a uniform distribution on the interval [0, 1).

Parameters
  • input (Tensor) – The input multi-dimensional tensor which specifies shape. The dtype of input can be float16, float64, float8_e4m3fn, float32, bfloat16.

  • name (str|None, optional) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to api_guide_Name.

  • dtype (str|np.dtype|paddle.dtype|None, optional) – The data type of the output tensor. Supported data types: float16, float64, float8_e4m3fn, float32, bfloat16. If dtype is None, the data type is the same as input’s data type. Default is None.

  • device (str|paddle.Place|None, optional) – The device on which to place the created tensor. If None, the device is the same as input’s device. Default is None.

  • requires_grad (bool, optional) – Whether to compute gradients for the created tensor. Default is False.

Returns

A Tensor with the same size as input that is filled with random numbers from a uniform distribution on the interval [0, 1).

Return type

Tensor

Examples

>>> import paddle

>>> # example 1:
>>> # dtype is None and the dtype of input is float32
>>> x = paddle.zeros((2, 3)).astype("float32")
>>> out1 = paddle.rand_like(x)
>>> print(out1)
>>> 
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.34962332, 0.82356787, 0.91275704],
 [0.12328923, 0.58439839, 0.32735515]])
>>> 
>>> print(out1.dtype)
paddle.float32

>>> # example 2:
>>> # dtype is None and the dtype of input is float64
>>> x = paddle.zeros((2, 3)).astype("float64")
>>> out2 = paddle.rand_like(x)
>>> print(out2)
>>> 
Tensor(shape=[2, 3], dtype=float64, place=Place(cpu), stop_gradient=True,
[[0.73964721, 0.28413662, 0.91918457],
 [0.62838351, 0.39185921, 0.51561823]])
>>> 
>>> print(out2.dtype)
paddle.float64

>>> # example 3:
>>> # dtype is float64 and the dtype of input is float32
>>> x = paddle.zeros((2, 3)).astype("float32")
>>> out3 = paddle.rand_like(x, dtype="float64")
>>> print(out3)
>>> 
Tensor(shape=[2, 3], dtype=float64, place=Place(cpu), stop_gradient=True,
[[0.84492219, 0.11572551, 0.73868765],
 [0.90269387, 0.45644298, 0.28739912]])
>>> 
>>> print(out3.dtype)
paddle.float64

>>> # example 4:
>>> # with requires_grad=True
>>> x = paddle.zeros((2, 2)).astype("float32")
>>> out4 = paddle.rand_like(x, requires_grad=True)
>>> print(out4.stop_gradient)
False