博客
关于我
Python 多处理 Numpy 随机
阅读量:802 次
发布时间:2023-03-07

本文共 1269 字,大约阅读时间需要 4 分钟。

在Python中处理Numpy的随机数时,多线程或多进程环境可能会导致无法准确复现随机序列的问题。以下是解决方案:

方法一:固定种子

为每个进程设置不同的随机种子,确保每次执行时生成的随机数序列完全一致。

import numpy as npfrom multiprocessing import Pool, current_process
def process_worker(n):    np.random.seed(current_process().name + str(n))    return np.random.randint(0, 100)
if __name__ == "__main__":    with Pool() as p:        print(list(p.map(process_worker, range(10))))

方法二:使用锁

在多线程环境下,利用GIL和互斥锁保护随机数序列的访问,避免并发修改导致的混乱。

import numpy as npfrom threading import Lock, current_threadfrom concurrent.futures import ThreadPoolExecutor
random_seed = 0random_lock = Lock()
def process_worker():    global random_seed    with random_lock:        np.random.seed(current_thread().name + str(random_seed))        random_seed += 1        return np.random.randint(0, 100)
if __name__ == "__main__":    with ThreadPoolExecutor() as executor:        print(list(executor.map(process_worker, range(10))))

方法三:使用Numpy的种子设置函数

直接调用Numpy的np.random.seed()函数设置种子,适用于无需多进程或多线程共享随机数序列的情况。

import numpy as np
def process_worker(n):    np.random.seed(n)    return np.random.randint(0, 100)
if __name__ == "__main__":    print([process_worker(i) for i in range(10)])

以上方法通过不同的方式确保多进程或多线程环境下可以准确复现随机数序列。current_process().name + str(n)和current_thread().name + str(random_seed)用于生成唯一的随机种子。

转载地址:http://onofk.baihongyu.com/

你可能感兴趣的文章
PYTHON-返回给定x的多边形路径的y坐标
查看>>
python-进程池与线程池,协程
查看>>
Python-通过函数传递变量
查看>>
Python内置函数详解——总结篇
查看>>
Python.对象集合中的标识.和散列
查看>>
Python.硒.拖放错误“AttributeError:move_to 需要 WebElement“
查看>>
Python内置函数详解
查看>>
Python/Kivy:从一个类调用函数到另一个类并在 Python 中显示小部件
查看>>
Python/Kivy:我可以在双击标签时调用函数吗
查看>>
python内置函数5-frozenset()
查看>>
Python/Plotly:如何使用要显示的信息自定义悬停模板?
查看>>
Python/Selenium - 无法单击 www.instagram.com 上的“接受 cookie“按钮
查看>>
Python内置函数(35)——next
查看>>
python写入mysql
查看>>
python写入csv老是乱码或者各种不好
查看>>
Python内置函数
查看>>
Python2 安装MySQLdb库
查看>>
Python2 已终结,入手Python 3,你需要这30个技巧
查看>>
python写下拉列表在excel,无法使用python获取Excel下拉列表(组合框)值
查看>>
python2.7安装
查看>>