randint
- paddle. randint ( low=0, high=None, shape=[1], dtype=None, name=None, *, out=None, device=None, pin_memory=False, requires_grad=False ) [源代码]
返回服从均匀分布的、范围在[low, high)的随机 Tensor,形状为 shape,数据类型为 dtype。当 high 为 None 时(默认),均匀采样的区间为[0, low)。
参数
low (int,可选) - 要生成的随机值范围的下限,
low包含在范围中。当high为 None 时,均匀采样的区间为[0,low)。默认值为 0。high (int,可选) - 要生成的随机值范围的上限,
high不包含在范围中。默认值为 None,此时范围是[0,low)。shape (list|tuple|Tensor,可选) - 生成的随机 Tensor 的形状。如果
shape是 list、tuple,则其中的元素可以是 int,或者是形状为[]且数据类型为 int32、int64 的 0-D Tensor。如果shape是 Tensor,则是数据类型为 int32、int64 的 1-D Tensor。默认值为[1]。别名size。dtype (str|paddle.dtype|np.dtype,可选) - 输出 Tensor 的数据类型,支持 int32、int64。当该参数值为 None 时, 输出 Tensor 的数据类型为 int64。默认值为 None。
name (str,可选) - 具体用法请参见 api_guide_Name,一般无需设置,默认值为 None。
关键字参数
out (Tensor,可选) - 输出 Tensor,若不为
None,计算结果将保存在该 Tensor 中,默认值为None。device (PlaceLike,可选) - 返回 Tensor 所在的设备。默认值为
None。pin_memory (bool,可选) - 如果设置为 True,返回的 Tensor 将分配在锁页内存中。默认值为 False。
requires_grad (bool,可选) - 是否需要自动求导记录返回 Tensor 上的操作。默认值为 False。
返回
服从均匀分布的、范围在[
low,high)的随机 Tensor,形状为shape,数据类型为dtype。
代码示例
>>> import paddle
>>> # example 1:
>>> # attr size is a list which doesn't contain Tensor.
>>> out1 = paddle.randint(low=-5, high=5, size=[2, 3])
>>> print(out1)
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[-1, 4, 4],
[-2, -5, -2]])
>>> # example 2:
>>> # attr size is a list which contains Tensor.
>>> dim1 = paddle.to_tensor(2, 'int64')
>>> dim2 = paddle.to_tensor(3, 'int32')
>>> out2 = paddle.randint(low=-5, high=5, size=[dim1, dim2])
>>> print(out2)
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[-4, -4, 2],
[-3, -1, -5]])
>>> # example 3:
>>> # attr size is a Tensor
>>> shape_tensor = paddle.to_tensor([2, 3])
>>> out3 = paddle.randint(low=-5, high=5, size=shape_tensor)
>>> print(out3)
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[-1, 4, -3],
[ 1, 2, -1]])
>>> # example 4:
>>> # data type is int32
>>> out4 = paddle.randint(low=-5, high=5, size=[3], dtype='int32')
>>> print(out4)
Tensor(shape=[3], dtype=int32, place=Place(cpu), stop_gradient=True,
[4, 4, 0])
>>> # example 5:
>>> # Input only one parameter
>>> # low=0, high=10, shape=[1], dtype='int64'
>>> out5 = paddle.randint(10)
>>> print(out5)
Tensor(shape=[1], dtype=int64, place=Place(cpu), stop_gradient=True,
[7])
>>> # example 6:
>>> # Use 'size' as an alias for 'shape'
>>> out6 = paddle.randint(high=10, size=[2, 3])
>>> print(out6.shape)
paddle.Size([2, 3])
>>> # example 7:
>>> # Use requires_grad=True so that stop_gradient=False
>>> out7 = paddle.randint(high=10, size=[2, 3], requires_grad=True)
>>> print(out7.stop_gradient)
False