np.random.randint:Numpy中的随机数

286 阅读2分钟

在Python中生成随机数很容易,因为它提供了一个随机numpy包。 在从事机器学习项目时,你需要创建一个由随机整数和数字组成的基本数据集。使用np.random.randint() 函数,你可以创建一个随机的整数。

np.random.randint

np.random.randint()是一个生成随机整数的numpy函数。 np.random.randint() 函数存在于numpy 的unexpected类中。

语法

random.randint( low, high = None, size = None, dtype = int)

参数

low这是该数字的起始范围。它是应该由这个函数生成的最低整数。如果在 low 参数中给出 1,这个函数将生成一个大于或等于 1 但不小于 1 的数字。

这是该数字的结束范围。它是由np.random.randint()函数生成的最高整数。默认情况下,它被设置为。因此,**np.random.randint()**函数生成的随机数最高为无穷大。如果高参数固定为某个值n,**np.random.randint()**函数会生成一个小于或等于n的数字,不会生成大于n的数字。

size这是输出元素的尺寸。如果提供的是单维度,就会以指定的尺寸创建一个单一的列表。如果提供了多维度,它将产生一个多维列表或元组。大小可以给定为( m, n, k )。然后生成 m * n * k 的值。

dtype这是输出生成值的数据类型。这代表了数据类型。默认情况下,它被设置为int

用于创建随机整数的Python程序

import numpy as np

# Creating variable for storing the random integer
res = np.random.randint(10)
print(res)

输出

4

我们导入了numpy ,在这个程序中使用numpy函数。我们使用了生成随机 整数的**随机int()**函数。

在这个程序中,我们给出的终点限制是10。因此,数字将在0-0 10之间生成。最后,我们打印了这个整数。这个数字在你每次运行该程序时都会不断变化,因为它返回的是一个随机数。

用于创建一系列随机整数的Python程序

import numpy as np

# Creating variable for storing the random integer

res = np.random.randint(5, 10, (3, 3, 3))

# Printing the shape of the created random integer array
print(res.shape)
print(res)

输出

(3, 3, 3)

[[[8 6 7]
 [8 5 5]
 [9 9 6]]

 [[5 5 5]
 [9 7 7]
 [8 8 6]]

 [[6 9 8]
 [7 9 6]
 [7 6 7]]]

在这个程序中,我们创建一个由随机整数组成的3 X 3 X 3的矩阵。整数的范围从5到10。结果数组的大小为3 X 3 X 3。

如果你每次都运行上述程序,输出会不断变化。因为它是随机的,所以每次我们运行这个程序时,数组中的值都会不断变化。

numpy random randint()函数就到此为止。