主要知识点:
创建随机ndarray数组主要包含设置随机种子、均匀分布和正态分布三部分内容,具体代码如下所示。
# 可以多次运行,观察程序输出结果是否一致
# 如果不设置随机数种子,观察多次运行输出结果是否一致
np.random.seed(10)
a = np.random.rand(3, 3)
a
array([[0.77132064, 0.02075195, 0.63364823], [0.74880388, 0.49850701, 0.22479665], [0.19806286, 0.76053071, 0.16911084]])
# 生成均匀分布随机数,随机数取值范围在[0, 1)之间
a = np.random.rand(3, 3)
a
array([[0.08833981, 0.68535982, 0.95339335], [0.00394827, 0.51219226, 0.81262096], [0.61252607, 0.72175532, 0.29187607]])
# 生成均匀分布随机数,指定随机数取值范围和数组形状
a = np.random.uniform(low = -1.0, high = 1.0, size=(2,2))
a
array([[ 0.83554825, 0.42915157], [ 0.08508874, -0.7156599 ]])
# 生成标准正态分布随机数
a = np.random.randn(3, 3)
a
array([[ 1.484537 , -1.07980489, -1.97772828], [-1.7433723 , 0.26607016, 2.38496733], [ 1.12369125, 1.67262221, 0.09914922]])
# 生成正态分布随机数,指定均值loc和方差scale
a = np.random.normal(loc = 1.0, scale = 1.0, size = (3,3))
a
array([[2.39799638, 0.72875201, 1.61320418], [0.73268281, 0.45069099, 1.1327083 ], [0.52385799, 2.30847308, 1.19501328]])
# 生成一维数组
a = np.arange(0, 30)
print('before random shuffle: ', a)
# 打乱一维数组顺序
np.random.shuffle(a)
print('after random shuffle: ', a)
('before random shuffle: ', array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]))
('after random shuffle: ', array([10, 21, 26, 7, 0, 23, 2, 17, 18, 20, 12, 6, 9, 3, 25, 5, 13,
14, 24, 29, 1, 28, 11, 15, 27, 16, 19, 4, 22, 8]))
随机打乱2维ndarray数组顺序,发现只有行的顺序被打乱了,列顺序不变,代码如下所示。
# 生成一维数组
a = np.arange(0, 30)
# 将一维数组转化成2维数组
a = a.reshape(10, 3)
print('before random shuffle: \n{}'.format(a))
# 打乱一维数组顺序
np.random.shuffle(a)
print('after random shuffle: \n{}'.format(a))
before random shuffle:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]
[15 16 17]
[18 19 20]
[21 22 23]
[24 25 26]
[27 28 29]]
after random shuffle:
[[15 16 17]
[12 13 14]
[27 28 29]
[ 3 4 5]
[ 9 10 11]
[21 22 23]
[18 19 20]
[ 0 1 2]
[ 6 7 8]
[24 25 26]]
# 随机选取部分元素
a = np.arange(30)
b = np.random.choice(a, size=5)
b
array([ 0, 24, 12, 5, 4])
import numpy as np
def func1():
# 可以多次运行,观察程序输出结果是否一致
# 如果不设置随机数种子,观察多次运行输出结果是否一致
np.random.seed(5)
a = np.random.rand(3, 3)
np.random.seed(None)
print(a)
# 生成均匀分布随机数,随机数取值范围在[0, 1)之间
a = np.random.rand(3, 3)
print(a)
# 生成均匀分布随机数,指定随机数取值范围和数组形状
a = np.random.uniform(low=-1.0, high=1.0, size=(2, 2))
print(a)
def func2():
# 生成标准正态分布随机数
print("正太分布:rand_n")
a = np.random.randn(3, 3)
print(a)
# 生成正态分布随机数,指定均值loc和方差scale
a = np.random.normal(loc=1.0, scale=1.0, size=(3))
print(a)
def func3():
a = np.arange(0, 30)
print('before random shuffle: ', a)
np.random.shuffle(a)
print("after random shuffle: ", a)
# 转为二维的,10 * 3
a = a.reshape(10, 3)
print(a)
np.random.shuffle(a)
print(a)
# 随机选取元素
print("random choice")
a = np.arange(30)
a.reshape(10, 3)
b = np.random.choice(a, size=5)
print(b)
if __name__ == "__main__":
# func1()
# func2()
func3()