目录
random.seed()以及random.shuffle(list)注意

我们调用 random.random() 生成随机数时,每一次生成的数都是随机的。但是,当我们预先使用 random.seed(x) 设定好种子之后,其中的 x 可以是任意数字,如10,这个时候,先调用它的情况下,使用 random() 生成的随机数将会是同一个。

注意:seed()确定后,实际上是生成了一组确定的随机数,在同一个程序中每一次调用random()或者shuffle()方法生成的仍然不同,因为随机数的不同,但是如果退出程序重新运行,那么两次的结果是一致的。

注意:seed()是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法。

1
2
3
# 生成同一个随机数
random.seed( 10 )
print "Random number with seed 10 : ", random.random()

random.shuffle()只能对list使用,不能对numpy.array使用

原因见源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def shuffle(self, x, random=None):
"""Shuffle list x in place, and return None.

Optional argument random is a 0-argument function returning a
random float in [0.0, 1.0); if it is the default None, the
standard random.random will be used.

"""

if random is None:
randbelow = self._randbelow
for i in reversed(range(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = randbelow(i+1)
x[i], x[j] = x[j], x[i] ###这一部分
else:
_int = int
for i in reversed(range(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = _int(random() * (i+1))
x[i], x[j] = x[j], x[i]

错误的原因在于np.array不能这样交换维度

1
2
3
4
5
6
7
8
9
arr2 = np.array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])
random.shuffle(arr2)
print(arr2)
output:
[[1 2 3]
[1 2 3]
[1 2 3]]

对于array正确的交换维度的方式应该是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
交换第 0 行和第 2 行:

>> P[[0, 2], :] = P[[2, 0], :]
# P[(0, 2), :] = P[(2, 0), :]
>> P
array([[ 0., 0., 1.],
[ 0., 1., 0.],
[ 1., 0., 0.]])

再交换第一列和第三列:

>> P[:, [0, 2]] = P[:, [2, 0]]
>> P
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])

而回到开始,想对array使用shuffle方法,应该是调用numpy自带的numpy.random.shuffle() 方法。

文章作者: HazardFY
文章链接: http://hazardfy.github.io/2019/11/16/random-seed-以及random-shuffle-list-注意/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 HazardFY's BLOG
打赏
  • 微信
  • 支付寶