如何在Python中设置全局随机种子 [英] How To Set Global Random Seed in Python

查看:99
本文介绍了如何在Python中设置全局随机种子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与R一样,我想为整个脚本/会话全局设置一个随机种子,而不是每次执行函数或运行模型时都必须调用随机种子函数.我知道sci-kit learning使用numpy RNG,但是也找不到全局设置它的方法.

Like in R, I would like to set a random seed globally for the entire script/session, instead of having to call the random seed function every time I execute a function or run a model. I am aware that sci-kit learn uses the numpy RNG, but also could not find a way to set it globally.

我在此处阅读了有关该主题的几篇文章,例如: Python中numpy.random和random.random之间的区别

I have read several posts here on this topic, such as this one: Differences between numpy.random and random.random in Python

它解释了两个RNG类之间的区别,但没有说明如何全局设置它.

It explains the difference between the two RNG classes, but not how to set it globally.

除了每次我希望输出都相同时都调用随机种子外,没有其他方法可以做到这一点吗?

Is there no way of doing this except for calling the random seed EVERY time I want the output to be the same?

## Random Library

import random
##### Random seed given
random.seed(42)
print(random.random()) #will generate a random number 

##### No seed given
print(random.random()) #will generate a random number 

##### Random seed given
random.seed(42)
print(random.random()) #will generate a random number 


#############################

## Numpy Library

import numpy as np

##### Random seed given
np.random.seed(42)
print(np.random.random())

##### No seed given
print(np.random.random())

##### Same seed given
np.random.seed(42)
print(np.random.random())

推荐答案

您的问题似乎与随机数生成器的整体思想背道而驰(在获取确定性结果的情况下有效).通常,您希望使用一些随机数生成器作为种子该值将更改程序的每次执行(或不同的数字,例如为会话设置一些cookie编号).例如,当前时间是经常使用的种子.之所以不会自动发生,是因为您可以根据需要提供特定的种子来获得确定性的序列.

Your question looks contrary to whole idea of random number generator(valid in case for getting deterministic results).Generally, you want to seed your random number generator with some value that will change each execution (or different number eg. set some cookie no for a session) of the program. For instance, the current time is a frequently-used seed. The reason why this doesn't happen automatically is so that if you want, you can provide a specific seed to get a deterministic sequence.

回到您的问题,如果您想拥有全局种子并希望使用该种子生成随机数.然后,您可以具有将所有内容结合在一起并随时调用的功能.

Coming back to your question, if you want to have global seed and wanted to generate random with that seed. Then you can have a function to club both things and call whenever you want.

def same_seed_random()
     np.random.seed(42)
     print(np.random.random())

我鼓励您在random seed @ https://pynative.com上查看更多内容./python-random-seed/

I would encourage you to check this for more on random seed@ https://pynative.com/python-random-seed/

这篇关于如何在Python中设置全局随机种子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆