numpy生成随机数组

1. 生成随机小数数组

语法

numpy.random.random(size)
参数说明:
  • size:形状,tuple类型,表示生成m行n列数组
返回值:

ndarray对象

例子:生成长度是10的一维数组

import numpy as np

arr = np.random.random((10,))
print(arr)
print('形状:',arr.shape)

执行结果:

[0.27192515 0.24172987 0.0509928  0.24029639 0.14075651 0.66891781
 0.27214572 0.7230067  0.22892616 0.1914595 ]
形状: (10,)

例子:生成2行3列数组

import numpy as np

arr=np.random.random((2,3))
print (arr)
print('形状:',arr.shape)

执行结果:

[[0.05505134 0.24072796 0.27501577]
 [0.45690823 0.69376541 0.77678054]]
形状: (2, 3)

2. 生成随机整数数组

语法

numpy.random.randint(low,high,size)
参数说明:
  • low:随机数范围的最小值,包含
  • high:随机数范围的最大值,不包含
  • size:形状,tuple类型,表示生成m行n列数组
返回值:

ndarray对象

例子 1

生成长度是5的一维数组,随机范围是1-10(不包含)

import numpy as np

arr = np.random.randint(1,10,(5,))

print(arr)
print('形状:',arr.shape)

执行结果:

[1 1 7 7 1]
形状: (5,)

例子 2

生成3行4列数组,随机范围是100-200(不包含)

import numpy as np

arr = np.random.randint(100,200,(3,4))

print(arr)
print('形状:',arr.shape)

执行结果:

[[173 116 140 105]
 [129 103 144 100]
 [109 151 199 163]]
形状: (3, 4)

设置随机数种子

计算机生成的是 伪随机数 ,就是计算机产生的随机数既 随机 又有 规律 。

通过设置 随机数种子,可以生成 相同的随机数组

import numpy as np

np.random.seed(10)
arr=np.random.randint(1,10,(2,3))

np.random.seed(10)
arr2=np.random.randint(1,10,(2,3))
print('arr:\n',arr)
print('arr2:\n',arr2)

多次执行上面的代码,执行结果如下:

arr:
 [[5 1 2]
 [1 2 9]]
arr2:
 [[5 1 2]
 [1 2 9]]

原文出处:/show_1EF3kpGz6vy8.html