简体   繁体   English

python随机种子进度如何保存?

[英]How to save python random seed progress?

I am training a reinforcement learning program on Colab and wish to maintain its reproducibility so I set random seeds at the beginning by我正在 Colab 上训练强化学习程序并希望保持其可重复性,所以我在开始时设置了随机种子

import random
random.seed(1)
import numpy as np
np.random.seed(1)

The problem is that Colab would kill my execution from time to time, so I will need to save some checkpoints such as model parameters in order for it to continue.问题是 Colab 会不时终止我的执行,所以我需要保存一些检查点,例如 model 参数,以便它继续。 Now my question is how may I save the "seeding" progress?现在我的问题是如何保存“播种”进度? I found that if I reinit my seed while resuming, the random numbers generated go back to the initial execution.我发现如果我在恢复时重新初始化我的种子,生成的随机数 go 回到初始执行。

For instance例如

>>> random.seed(40)
>>> random.random()
0.4586
>>> random.random()
0.8778
# the next is >>> random.random()
#             0.0318

# while continue execution
>>> random.seed(40)
>>> random.random()
0.4586        # I want this to be 0.0318

Thanks!谢谢!

Thanks for @jasonharper's comment for pointing out the right direction!感谢@jasonharper 的评论指出了正确的方向!

  1. For random module, use getstate() and setstate().对于随机模块,使用 getstate() 和 setstate()。

eg例如

>>> random.seed(40)
>>> random.random()
0.4586
>>> random.random()
0.8778
>>> state = random.getstate()
>>> random.random()
0.0318
>>> random.setstate(state)
>>> random.random()
0.0318

ref - https://www.w3schools.com/python/ref_random_setstate.asp参考 - https://www.w3schools.com/python/ref_random_setstate.asp

  1. For numpy.random, use get_state() and set_state().对于 numpy.random,使用 get_state() 和 set_state()。 Here's how it works这是它的工作原理

eg例如

>>> import numpy as np
>>> np.random.seed(1)
>>> np.random.rand(1,1)
array([[0.417022]])
>>> state = np.random.get_state()
>>> np.random.rand(1,1)
array([[0.72032449]])
>>> np.random.set_state(state)
>>> np.random.rand(1,1)
array([[0.72032449]])

ref - https://numpy.org/doc/stable/reference/random/generated/numpy.random.get_state.html;参考 - https://numpy.org/doc/stable/reference/random/generated/numpy.random.get_state.html; https://numpy.org/doc/stable/reference/random/generated/numpy.random.set_state.html#numpy.random.set_state https://numpy.org/doc/stable/reference/random/generated/numpy.random.set_state.html#numpy.random.set_state

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM