gpt4 book ai didi

Python共享读内存

转载 作者:太空狗 更新时间:2023-10-30 00:05:47 24 4
gpt4 key购买 nike

我正在处理一个大约 8GB 的​​数据集,我还使用 scikit-learn 在其上训练各种 ML 模型。数据集基本上是一维整数向量列表。

如何使数据集可用于多个 Python 进程,或者如何对数据集进行编码以便使其使用 multiprocessing 的类?我一直在阅读 ctypes,也一直在阅读 multiprocessing 的文档,但我很困惑。我只需要让数据对每个进程都可读,这样我就可以用它来训练模型。

我是否需要将共享的 multiprocessing 变量作为 ctypes?

如何将数据集表示为 ctypes

最佳答案

我假设您能够以 numpy 数组的形式将整个数据集加载到 RAM 中,并且您正在 Linux 或 Mac 上工作。 (如果你在 Windows 上或者你不能将数组放入 RAM,那么你应该将数组复制到磁盘上的文件并使用 numpy.memmap 访问它。你的计算机也会将数据从磁盘缓存到 RAM 中尽可能地,并且这些缓存将在进程之间共享,因此这不是一个糟糕的解决方案。)

在上述假设下,如果您需要对通过 multiprocessing 创建的其他进程中的数据集进行只读访问,您可以简单地创建数据集,然后启动其他进程。他们将对原始命名空间中的数据具有只读访问权限。它们可以更改原始命名空间中的数据,但这些更改对其他进程不可见(内存管理器会将它们更改的每个内存段复制到本地内存映射中)。

如果您的其他进程需要更改原始数据集并使这些更改对父进程或其他进程可见,您可以使用如下方式:

import multiprocessing
import numpy as np

# create your big dataset
big_data = np.zeros((3, 3))

# create a shared-memory wrapper for big_data's underlying data
# (it doesn't matter what datatype we use, and 'c' is easiest)
# I think if lock=True, you get a serialized object, which you don't want.
# Note: you will need to setup your own method to synchronize access to big_data.
buf = multiprocessing.Array('c', big_data.data, lock=False)

# at this point, buf and big_data.data point to the same block of memory,
# (try looking at id(buf[0]) and id(big_data.data[0])) but for some reason
# changes aren't propagated between them unless you do the following:
big_data.data = buf

# now you can update big_data from any process:
def add_one_direct():
big_data[:] = big_data + 1

def add_one(a):
# People say this won't work, since Process() will pickle the argument.
# But in my experience Process() seems to pass the argument via shared
# memory, so it works OK.
a[:] = a+1

print "starting value:"
print big_data

p = multiprocessing.Process(target=add_one_direct)
p.start()
p.join()

print "after add_one_direct():"
print big_data

p = multiprocessing.Process(target=add_one, args=(big_data,))
p.start()
p.join()

print "after add_one():"
print big_data

关于Python共享读内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38817914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com