python - Random seed not performing as expected
问题描述
I'm running a cosimulation and setting the seed at the start of the program. I'm drawing from a joint lognormal distribution. This is my function:
def get_new_EV(numEVs):
# numEVs is the number of EVs to return to the main program
lvl2 = np.random.lognormal(np.random.normal(5,1),np.random.uniform(0,2),1)
lvl1 = np.random.lognormal(np.random.normal(3,1),np.random.uniform(0,10),1)
lvl3 = np.random.lognormal(np.random.normal(2,1),np.random.uniform(0,.1),1)
total = lvl1+lvl2+lvl3
#print(lvl1,lvl2,lvl3,total)
p1,p2,p3 = lvl1/total,lvl2/total,lvl3/total
#print(p1,p2,p3)
listOfEVs = np.random.choice([1,2,3],numEVs,p=[p1[0],p2[0],p3[0]]).tolist()
numLvl1 = listOfEVs.count(1)
numLvl2 = listOfEVs.count(2)
numLvl3 = listOfEVs.count(3)
return numLvl1,numLvl2,numLvl3,listOfEVs
In the main program, I execute this:
if __name__ == "__main__":
random.seed(1)
print('test seed: ',get_new_EV(2))
The output of running the program two times is this:
test seed: (0, 0, 2, [3, 3])
test seed: (2, 0, 0, [1, 1])
I don't understand -- the seed is the same. Shouldn't the output be the same? Isn't that the point of random.seed() ?
解决方案
正如@Barmar 提到np.random.seed()
的是一个遗留功能,文档提到了推荐的播种方式。
从用于播种 numpy.random 相关调用的 numpy 文档中:
https://numpy.org/doc/stable/reference/random/generated/numpy.random.seed.html
from numpy.random import MT19937
from numpy.random import RandomState, SeedSequence
rs = RandomState(MT19937(SeedSequence(123456789)))
推荐阅读
- javascript - 如何修复表格?
- visual-studio-code - 如果需要,为整个 VSCode 和每个项目设置特定的环境变量,以及如何为测试设置环境(Flask 图标)?
- mysql - 我的代码有什么可以改变的吗?
- python - bot 在问题 discord.py 中插入命令
- ios - 触摸功能在 SpriteKit 中不起作用吗
- css - 如何添加反应样式不重复
- react-table - 如何从 v7 (React-Table) 中的列访问另一列的值
- javascript - 安装反应后显示错误:目标容器不是 DOM 元素
- express - 在 swagger-jsdoc 中参考猫鼬模式定义?
- javascript - 如何使用 jquery append 函数增加产品数量