Python自定义列表构建优化

时间:2018-07-18 19:05:10

标签: python optimization artificial-intelligence genetic-algorithm

我正在用Python编程遗传算法,但是,对于重量为300万的个体(每个个体都是3.000.000个元素的列表),我的运算符(MMX)花费的时间太长(10秒)。 >

这是操作员的代码:

def calc_gen(maxel, minel, rec1, rec2, phiC):
    g = maxel - minel
    phi = 0
    if g > phiC:
        # Recta 2
        phi = rec2[0] * g + rec2[1]
    elif g < phiC:
        # Recta 1
        phi = rec1[0] * g + rec1[1]
    #Hay que asegurarse que no nos salimos del rango:
    maxv = min(1, maxel - phi)
    minv = max(0, minel + phi)
    gen1 = random.uniform(minv, maxv)  # Guardar el gen del primer hijo
    # Si C es el centro y A el elemento que ya tenemos y B el simétrico de A: C - A + C = B -> 2C - A = B
    # C = (maxv + minv) / 2; 2C - A = B -> maxv + minv - A = B
    # center = (maxv + minv) / 2
    gen2 = maxv + minv - gen1
    return gen1, gen2
    #return gen1, maxv + minv - gen1

def cxMMX(poblacion, rec1, rec2, phiC):
    start = timer()
    # Calcular el maximo y el minimo de cada gen en toda la población
    max_genes = numpy.amax(poblacion, axis=0).tolist()
    min_genes = numpy.amin(poblacion, axis=0).tolist()
    gis = timer()
    hijo1 = Individual()
    hijo2 = Individual()
    # Iterar dos listas a la vez (zip) con su indice (enumerate). Así crearemos los hijos simultáneamente en un loop
    for i, (maxel, minel) in enumerate(zip(max_genes, min_genes)):
        gen1, gen2 = calc_gen(maxel, minel, rec1, rec2, phiC)
        hijo1.append(gen1)
        hijo2.append(gen2)
    end = timer()
    #print("Tiempo Gi: %f Tiempo init: %f Tiempo calc gen: %f Tiempo mate total: %f" % (gis-start, init-gis, end-init, end-start))
    return [hijo1, hijo2]

rec1,rec2和phiC是确定如何完成交叉的参数,您不必理会它们。在整个算法中,它们具有相同的值。

poblacion是一个列表列表,可以说它的形状是[7,3000000]。 Individual()是一个自定义类。它基本上是继承“列表”并添加一些属性来存储适应度值。

分别执行numpy.amax和numpy.amin似乎需要做额外的工作。另外,可能还有一种更Python化的方式来执行“ calc_gen()”循环。

PD:“ gen1”取决于“ gen2”:gen1在一定范围内随机获得,然后获得gen2以寻找对称点。

PD2:在original paper上可以找到有关MMX运算符的更详细的说明,但是,您可以假设代码是可以的,并且可以执行此操作。 Doi是https://doi.org/10.1007/3-540-44522-6_73

PD:enumerate()和i在旧代码中,忘记删除它们!

编辑:使用Dillon Davis的解决方案将时间减少了20%。这是一个非常干净的解决方案,它将与任何自定义列表构建函数一起使用,只要您通过执行一个函数来获取列表的每个值即可:

def calc_gen_v2(maxel,minel, rec1m, rec1b, rec2m, rec2b, phiC):
    g = maxel - minel
    phi = 0
    if g > phiC:
        # Recta 2
        phi = rec2m * g + rec2b
    elif g < phiC:
        # Recta 1
        phi = rec1m * g + rec1b
    #Hay que asegurarse que no nos salimos del rango:
    maxv = min(1, maxel - phi)
    minv = max(0, minel + phi)
    gen1 = random.uniform(minv, maxv)  # Guardar el gen del primer hijo
    # Si C es el centro y A el elemento que ya tenemos y B el simétrico de A: C - A + C = B -> 2C - A = B
    # C = (maxv + minv) / 2; 2C - A = B -> maxv + minv - A = B
    # center = (maxv + minv) / 2
    gen2 = maxv + minv - gen1
    return gen1, gen2

def cxMMX_v3(poblacion, rec1, rec2, phiC):
    start = timer()
    # Calcular el maximo y el minimo de cada gen en toda la población
    max_genes = numpy.amax(poblacion, axis=0)
    min_genes = numpy.amin(poblacion, axis=0)
    gis = timer()
    hijo1, hijo2 = map(Individual, numpy.vectorize(calc_gen_v2)(max_genes, min_genes, rec1[0], rec1[1], rec2[0], rec2[1], phiC))
    end = timer()
    #print("Tiempo Gi: %f Tiempo init: %f Tiempo calc gen: %f Tiempo mate total: %f" % (gis-start, init-gis, end-init, end-start))
    return [hijo1, hijo2]

编辑2 :正如Dillon Davis所建议的那样,我以纯粹的numpy实现了它,将时间减少到了3.5秒! (节省65%的时间)

def cxMMX_numpy(poblacion, rec1, rec2, phiC):
    # Calculate max and min for every gen in the population
    max_genes = numpy.amax(poblacion, axis=0)
    min_genes = numpy.amin(poblacion, axis=0)
    g_pop = numpy.subtract(max_genes, min_genes)
    phi_pop = numpy.where(g_pop < phiC, numpy.multiply(g_pop, rec1[0]) + rec1[1], numpy.where(g_pop > phiC, numpy.multiply(g_pop, rec2[0]) + rec2[1], 0))
    maxv = numpy.minimum(numpy.subtract(max_genes, phi_pop), 1)
    minv = numpy.maximum(numpy.sum([min_genes, phi_pop], axis=0), 0)
    hijo1 = numpy.random.uniform(low=minv, high=maxv, size=minv.size)
    hijo2 = numpy.subtract(numpy.sum([maxv, minv], axis=0), hijo1)
    return [Individual(hijo1), Individual(hijo2)]

注意:如果要重复使用,个人将从列表中继承

注意:如果g = phiC,则rec1 [0] * g_pop + rec1 [1] = 0,总是,rec1 [0]和rec1 [1]保证!所以也许最好做数学而不是三重选择?

2 个答案:

答案 0 :(得分:3)

尝试将cxMMX()中的for循环替换为以下内容:

hijo1, hijo2 = map(Individual, numpy.vectorize(calc_gen)(max_genes, min_genes, rec1, rec2, phiC))

从您的.tolist()numpy.amin()中放下numpy.amax()

这将向量化您的calc_gen函数,避免多次.append()调用带来的压缩和函数开销,并且总体上应该要快得多。

编辑:

还可以考虑将calc_gen()转换为直接在numpy数组上工作。用random.uniform()numpy.random.uniform()min()将对max()的调用替换为numpy.minimum()numpy.maximum(),然后完全消除for循环/ map +向量化。最终,这将是最快的选择。

答案 1 :(得分:1)

您是否尝试过使用multiprocessing.Pool

您首先需要为calc_gen做一个包装器:

# after calc_gen def
def get_calc_gen(rec1, rec2, phiC):
    return lambda maxel, minel: calc_gen(maxel, minel, rec1, rec2, phiC)

然后代替for循环,您将执行以下操作:

# replacing for loop section
cgen = get_calc_gen(rec1, rec2, phiC)
minmax_genes = zip(max_genes, min_genes)
pool = multiprocessing.Pool()
mapped_genes = pool.map(cgen, minmax_genes)
for gen1, gen2 in mapped_genes:
    hijo1.append(gen1)
    hijo2.append(gen2)

P.S。由于您似乎并没有使用enumerate

,因此您在原始代码中不需要i