python中numpy.random.seed设置随机种子是否影响子进程

给出代码:

复制代码
from multiprocessing import Process
import numpy as np


class NN(Process):
    def __init__(self, id):
        super(NN, self).__init__()
        self.id = id
    def run(self):
        super(NN, self).run()
        print(np.random.random(5))
        print(np.random.random(5))

np.random.seed(1111)
print(np.random.random(5))
print(np.random.random(5))
print("="*30)
np.random.seed(1111)

ps = [NN(i) for i in range(1)]
for p in ps:
    p.start()

for p in ps:
    p.join()
复制代码

 

运行结果:

 

 ========================================

 

给出对比代码:

复制代码
from multiprocessing import Process
import numpy as np
import time


class NN(Process):
    def __init__(self, id):
        super(NN, self).__init__()
        self.id = id
    def run(self):
        super(NN, self).run()
        time.sleep(10)
        print(np.random.random(5))

np.random.seed(1111)
print(np.random.random(5))

ps = [NN(i) for i in range(1)]
for p in ps:
    p.start()

np.random.seed(1111)

for p in ps:
    p.join()
复制代码

 

运行结果:

 

 

-------------------------------------------------------------------

 

PS:

可以看到,在python生成多进程时会copy父进程中的numpy.random的状态,这其中也包括随机种子的状态; 如果子进程生成完成后,那么父进程中的numpy.random的状态是不会影响子进程的。

 

 

========================================================

posted on   Angry_Panda  阅读(72)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
历史上的今天:
2021-09-11 openAI的仿真环境Gym Retro的Python API接口

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示