rand¶
返回符合均匀分布的、范围在[0, 1)的 Tensor,形状为 shape
,数据类型为 dtype
。
参数¶
shape (list|tuple|Tensor) - 生成的随机 Tensor 的形状。如果
shape
是 list、tuple,则其中的元素可以是 int,或者是形状为[]且数据类型为 int32、int64 的 0-D Tensor。如果shape
是 Tensor,则是数据类型为 int32、int64 的 1-D Tensor。dtype (str|np.dtype,可选) - 输出 Tensor 的数据类型,支持 float32、float64。当该参数值为 None 时,输出 Tensor 的数据类型为 float32。使用全局默认 dtype(详细信息请见 get_default_dtype )。默认值为 None。
name (str,可选) - 具体用法请参见 Name,一般无需设置,默认值为 None。
返回¶
Tensor:符合均匀分布的范围为[0, 1)的随机 Tensor,形状为
shape
,数据类型为dtype
。
示例代码¶
>>> import paddle
>>> # example 1: attr shape is a list which doesn't contain Tensor.
>>> out1 = paddle.rand(shape=[2, 3])
>>> print(out1)
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.68532258, 0.69431782, 0.44835982],
[0.13204314, 0.48128194, 0.36574543]])
>>> # example 2: attr shape is a list which contains Tensor.
>>> dim1 = paddle.to_tensor(2, 'int64')
>>> dim2 = paddle.to_tensor(3, 'int32')
>>> out2 = paddle.rand(shape=[dim1, dim2, 2])
>>> print(out2)
Tensor(shape=[2, 3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[0.62102991, 0.45255184],
[0.81386960, 0.22463219],
[0.87946558, 0.28097662]],
[[0.36565998, 0.63203937],
[0.58640617, 0.92696166],
[0.85060406, 0.38138932]]])
>>> # example 3: attr shape is a Tensor, the data type must be int64 or int32.
>>> shape_tensor = paddle.to_tensor([2, 3])
>>> out3 = paddle.rand(shape_tensor)
>>> print(out3)
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.77650446, 0.12870903, 0.05153799],
[0.27029657, 0.03963696, 0.42487794]])