Python共享读取内存

Geo*_*iev 6 python ctypes python-2.7 scikit-learn python-multiprocessing

我正在处理一个大约8GB的数据集,我也在使用scikit-learn来训练各种ML模型.数据集基本上是一维的1D向量列表.

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

我需要将共享multiprocessing变量作为ctypes吗?

如何将数据集表示为ctypes

Mat*_*ipp 3

我假设您能够将整个数据集以 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
Run Code Online (Sandbox Code Playgroud)