Beispiel #1
0
    for i in range(len(x.genes)):
        weight += x.genes[i][0]
        value += x.genes[i][1]
    if weight <= 15:
        return value
    return 0


def print_func(x):
    result = ""
    count = collections.Counter(x)
    for repetitions in count.keys():
        if count.get(repetitions) != 0 and repetitions[0] != 0:
            result += str(count.get(repetitions)) + \
                "x" + str(repetitions) + ", "
    return result


if __name__ == "__main__":
    pop = Population(1000, 0.1, fitness_f, print_func)
    pop.generate_individuals(gene_f, 15)
    y1, y2, y3 = pop.evolve(iterations=ITERATIONS)
    plt.plot(range(pop.generation - 1), y1)
    plt.plot(range(pop.generation - 1), y2)
    plt.plot(range(pop.generation - 1), y3)
    plt.legend(["minimum fitness", "average fitness", "maximum fitness"],
               loc=1)
    plt.ylabel("fitness")
    plt.xlabel("generation")
    plt.show()
Beispiel #2
0
ITERATIONS = 50
"""search for the binary string specified here"""
word = list('0010101011010001001011')


def gene_f():
    """a gene is represented with a 1 or 0"""
    return random.choice(['0', '1'])


def fitness_f(x):
    """the fitness function compares the position of each gene 
    with the optimal"""
    n = 0
    for i in range(len(x.genes)):
        if word[i] == x.genes[i]:
            n += 1
    return n 

def print_func(x):
    result = ""
    for gene in x:
        result += gene
    return result + ", "


if __name__ == "__main__":
    pop = Population(100, 0.01, fitness_f, print_func)
    pop.generate_individuals(gene_f, len(word))
    pop.evolve(iterations=ITERATIONS, fitness_limit=len(word))