博客
关于我
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+requests+unittest执行接口自动化测试详情
查看>>
python+requests+unittest执行自动化接口测试!
查看>>
Python+Requests编码识别Bug
查看>>
python函数编写_[零基础学python]传说中的函数编写条规
查看>>
Python+selenium —— UI自动化之鼠标操作
查看>>
python函数注释,参数后面加冒号:,函数后面的箭头→是什么?
查看>>
Python+Selenium+Threading进行兼容性测试
查看>>
Python+selenium+unittest的GUI自动化框架实现
查看>>
python函数拟合不规则曲线_Python计算&绘图——曲线拟合问题(转)
查看>>
python函数定义的基本格式_零基础学python-2.19 定义函数、调用函数与默认参数
查看>>
Python+Selenium之数据驱动测试的实现
查看>>
python函数定义与使用+返回值简解
查看>>
Python+Selenium登录
查看>>
Python日期时间模块
查看>>
Python函数合集:足足68个内置函数请收好!
查看>>
Python+Selenium自动化测试项目实战
查看>>
Python+Selenium自动化测试项目实战【建议收藏】
查看>>
Python+Selenium自动化测试:Page Object模式
查看>>
python+selenium进行cnblog的自动化登录测试
查看>>
Python函数只返回第一个值而不是数据框
查看>>