python创建遗传算法没有收敛到最大或最小

时间:2018-04-04 14:21:01

标签: python max artificial-intelligence convergence genetic

您好我需要帮助创建遗传算法以收敛到最大值或最小值。 我为找到的最大句子ascii sum开发了一个代码,但是我的代码没有收敛到最大值,我的代码使得“yoyo”值

像这张照片: matploltib output

我分享我的代码:

import random
import statistics

EVOLUTION=[]

words = [
        ["Un", "Des", "Une", "On", "Elle"],
        ["a", "eu", "avait", "est", "était", "fut"],
        ["soif", "rouge"]
        ]

def individual(data):
    #return tuple(random.choice(range(len(feature))) for feature in data)
    return tuple(random.choice(range(len(feature))) for feature in data)


def population(data, initial=100):
    return [individual(data) for i in range(initial)]


def fitness(individual, data):
    chaine=sentence(individual,words)
    somme = 0
    for caractere in chaine:
        somme = somme + ord(caractere)

    print(chaine)
    print(somme)
    EVOLUTION.append(somme)
    return somme
    #return sum(data[i][individual[i]] for i in range(len(individual)))


def grade(population, data):
    fit = [fitness(ind, data) for ind in population]
    return statistics.mean(fit)


def mutate(ind, data):
    gene = random.randrange(0, len(ind))
    clone = list(ind)
    clone[gene] = random.randrange(0, len(data[gene]))
    #print(sentence(tuple(clone),words))
    return tuple(clone)


def cross(mother, father):
    return tuple(round(statistics.mean(genes)) for genes in zip(mother, father))

def sentence(individual, words):
    return ' '.join([words[i][individual[i]] for i in range(len(words))])

def evolve(population, data, retain=0.0, random_select=0.00, mutation_rate=0.00):
    def cmp_ind(ind):
        return fitness(ind, data)
    sorted_population = sorted(population, key=cmp_ind, reverse=True)

    len_retained = round(len(population) * retain)
    retained = sorted_population[:len_retained]

    random_selected = [
        ind
        for ind in sorted_population[len_retained:]
        if random.random() <= random_select
    ]

    mutated = [
        mutate(ind, data)
        for ind in sorted_population[len_retained:]
        if random.random() <= mutation_rate
    ]

    children = [
        cross(random.choice(sorted_population),
              random.choice(sorted_population))
        for i in range(len(population) - len(random_selected) - len(mutated))
    ]

    return random_selected + mutated + children




if __name__ == '__main__':

    data = [[len(w) for w in ws] for ws in words]



    initial_population = population(data, 30)
    next_population = initial_population
    max_iter = 3

    for i in range(max_iter):
        next_population = evolve(next_population, data)

    sorted_population = sorted(next_population, key=lambda x: fitness(x, data))
    best_individual = sorted_population[0]

    print("best solution :")

    chaine=sentence(best_individual,words)
    somme = 0
    for caractere in chaine:
        somme = somme + ord(caractere)
    print(chaine)
    print(somme)

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    plt.plot(EVOLUTION)
    plt.savefig('myfig')

我希望在我的健身功能中找到更高的解决方案

感谢您的帮助

0 个答案:

没有答案