我正在使用Deap框架实现遗传算法。 该算法有效,但我注意到GA的多进程版本内存消耗9 GB,而单进程2 GB,我怀疑因为它已为每个进程分配内存。实际上,一旦执行了映射,所使用的内存就会增加。 由于进程之间共享的数据仅用于读取,因此所有数据都可以访问相同的内存。
这是我的代码的结构。
def evaluate(individual, dataset=None):
penalty = dataset.compute(individual)
return penalty
def initialize():
dataset = dataset(file1, file2)
pool = multiprocessing.Pool()
toolbox.register("map", pool.map)
toolbox.register("evaluate", evaluate, dataset=dataset)
return toolbox, dataset
def main():
toolbox, dataset = initialize()
dataset.data = some_training_set
fitnesses = toolbox.map(toolbox.evaluate, population)
dataset.data = some_validation_set
fitnesses = toolbox.map(toolbox.evaluate, population)
然后我有一个包含数据集(使用pandas读取)和字典的类。
class Dataset:
def __init__(self, file1, file2):
self.data = read(file1)
self.dict = loadpickle(file2)
def compute(self, individual):
for row in self.data
# some stuff reading row and self.dict
分享内存的最简单方法是什么?我试图为self.data和self.dict使用全局变量,但没有...
答案 0 :(得分:2)
多处理模块使用多进程模型而不是线程模型,因此每个进程都不能共享内存(不使用共享内存IPC调用)。如果你需要它来共享内存,需要在引擎盖下重新设计Deap框架以使用线程。