簡體   English   中英

無法通過多處理加速 Python DEAP

[英]Unable to speed up Python DEAP with Multiprocessing

我正在使用 DEAP package 和多處理對 OneMax 問題(最大化位串的數量)使用以下示例代碼。

我無法使用多處理來加速這個過程。 在找出這里的問題之前,我想將其用於更復雜的問題。

謝謝你。

import array
import multiprocessing
from multiprocessing import Pool
import random
import time
import numpy as np

from deap import algorithms
from deap import base
from deap import creator
from deap import tools

creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", array.array, typecode='b', fitness=creator.FitnessMax)

toolbox = base.Toolbox()

toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 10000)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)


#OneMax problem is a simple problem consisting in maximizing the number of ones of a bitstring.
def evalOneMax(individual):
    return sum(individual),

toolbox.register("evaluate", evalOneMax)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)

if __name__ == "__main__":

    t1 = time.time()
    CPU_count = multiprocessing.cpu_count()-1

    p = Pool(CPU_count)
    toolbox.register("map", p.map)

    pop = toolbox.population(n=1000)
    hof = tools.HallOfFame(1)
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", np.mean)
    stats.register("std", np.std)
    stats.register("min", np.min)
    stats.register("max", np.max)

    algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=50, 
                        stats=stats, halloffame=hof)

    p.close()
    p.join()
    t2 = time.time()
    print("Multiprocessing with",CPU_count,"core(s) took",round((t2-t1),2),"s")

如果您在 windows 的交互式解釋器中運行代碼,請嘗試在 cmd 中運行它。 它在我的情況下有效。 在 DEAP 中使用多處理進行遺傳編程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM