[英]How to reuse workers from Pool for a genetic algorithm
I had a previous related question on this problem: Parallelize for loop in python 我之前有一个关于这个问题的相关问题: 在python中并行化循环
I have a genetic algorithm which I'm trying to speed up by parallelizing the evaluation function. 我有一个遗传算法,我试图通过并行化评估功能来加快速度。 The GA is a class and the code looks something like this:
GA是一个类,代码看起来像这样:
copy_reg.pickle(types.MethodType,lambda method: (getattr, (method.im_self, method.im_func.__name__)),getattr)
class GA:
...
...
def evaluation(self):
self.scores = Pool(processes=nprocs).map(self.costly_function,self.population)
def run(self):
self.initial_population()
self.evaluation()
while self.Gen > i:
self.select()
self.crossover()
self.mutation()
self.evaluation()
i += 1
This gives the right result compared to the sequential method but it is significantly slower. 与顺序方法相比,这给出了正确的结果,但速度明显变慢。 My guess is that this is because I'm creating a new group of process workers for each generation inside the while loop in the function
evaluation
. 我的猜测是,这是因为我在函数
evaluation
为while循环中的每一代创建了一组新的流程工作者。 Is there a way of reusing the workers so I can achieve a speed up? 有没有办法重复工人,所以我可以加快速度?
Solved the problem by adding the function below which I got from https://stackoverflow.com/a/25385582/4759898 通过添加我从https://stackoverflow.com/a/25385582/4759898获得的功能解决了这个问题
def __getstate__(self):
self_dict = self.__dict__.copy()
del self_dict['pool']
return self_dict
def __setstate__(self, state):
self.__dict__.update(state)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.