rand_like
返回一个与输入张量尺寸相同的张量,其元素为从区间 [0, 1) 上均匀分布中采样的随机数。
参数
input (Tensor) – 输入的多维 Tensor,用于指定输出张量的形状。数据类型可以是 float16、bfloat16、float32、float64。
name (str,可选) - 具体用法请参见 api_guide_Name,一般无需设置,默认值为 None。
dtype (str|np.dtype|paddle.dtype,可选) - 输出 Tensor 的数据类型,支持 float16、bfloat16、float32、float64。当该参数值为 None 时,输出 Tensor 的数据类型与输入 Tensor 的数据类型一致。该参数为仅关键字参数,默认值为 None。
device (str|paddle.Place,可选) - 指定创建 Tensor 的设备位置。如果为 None,则使用与输入 Tensor 相同的设备。该参数为仅关键字参数,默认值为 None。
requires_grad (bool,可选) - 是否为创建的 Tensor 计算梯度。该参数为仅关键字参数,默认值为 False。
返回
Tensor:与输入张量
input形状相同的 Tensor,其元素为从区间 [0, 1) 上均匀分布中采样的随机数,数据类型为dtype。
代码示例
>>> 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