随机种子的作用:固定之后 np 代码的随机性
也就是说,从设置随机种子之后所有的 numpy 代码产生的随机数都可复现。(一个常见误区是认为只有设置随机种子之后紧跟的一行代码可以复现)
import numpy as np
np.random.seed(0)
ls = [1,2,3,4,5,6,7,8,9,10]
ls = np.random.choice(ls, 10, replace=False)
print(ls)
ls = np.random.choice(ls, 10, replace=False)
print(ls)
ls = np.random.choice(ls, 10, replace=False)
print(ls)
rand_matrix = np.random.rand(3, 3)
print(rand_matrix)
第一次运行
[ 3 9 5 10 2 7 8 4 1 6]
[10 7 9 5 6 1 3 8 4 2]
[ 9 5 4 6 1 7 10 3 2 8]
[[0.64817187 0.36824154 0.95715516]
[0.14035078 0.87008726 0.47360805]
[0.80091075 0.52047748 0.67887953]]
第二次运行
[ 3 9 5 10 2 7 8 4 1 6]
[10 7 9 5 6 1 3 8 4 2]
[ 9 5 4 6 1 7 10 3 2 8]
[[0.64817187 0.36824154 0.95715516]
[0.14035078 0.87008726 0.47360805]
[0.80091075 0.52047748 0.67887953]]