Пример #1
0
def main():
    # Creating function optimalization model implementing genetic algorithm
    opt = Optimizer(target=function,
                    epochs=EPOCHS,
                    args_num=N,
                    x1_range=X1_RANGE,
                    x2_range=X2_RANGE,
                    precision=PRECISION,
                    population_size=POPULATION_SIZE,
                    type="min")

    # Initiation of pupulation
    opt.initPopulation()
    print(opt.population)

    # TEST : Decoding population's chtomosomes
    for x in opt.population:
        print(x.decode(), ", ", opt.target(x.decode()))

    # Evaluating current population
    opt.evaluate()

    # TEST : Selecting parents
    # Truncation
    best = opt.truncation(2)
    print("TRUNCATION : best = ", best, " decimal : ", best.decode(),
          "target : ", best.getTargetValue())
    # Tournament
    best = opt.tournament(0.3)
    print("TOURNAMENT : best = ", best, " decimal : ", best.decode(),
          "target : ", best.getTargetValue())

    # Roulette
    opt.normalizePopulation()
    best = opt.roulette()
    print("Roulette : best = ", best, " decimal : ", best.decode(),
          "target : ", best.getTargetValue())

    # Mutation
    print("MUTATION : ",
          opt.mutate(Chromosome([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 10), 2, 1))
    print("MUTATION EDGE : ",
          opt.mutateEdge(Chromosome([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 10), 2, 1))

    # Generating next generation with truncation
    # print("old pop : ", opt.population)
    # print("old pop decimal : ", [x.getTargetValue() for x in opt.population])
    # opt.nextGen("tournament", 5)
    # print("new pop : ", opt.population)
    # print("new pop decimal : ", [x.getTargetValue() for x in opt.population])

    # Proper optimalization of target function
    # opt.initPopulation()
    # print("~~~~~~~~~~~~~  OPTIMALIZATION  ~~~~~~~~~~~~~~~")
    # print("old pop : ", opt.population)
    # opt.evaluate()
    # print("old pop decimal : ", [x.getTargetValue() for x in opt.population])
    # opt.optimize()
    # print("new pop : ", opt.population)
    # print("new pop decimal : ", [x.getTargetValue() for x in opt.population])

    # GENEREAL TEST
    opt_test = Optimizer(target=function,
                         epochs=EPOCHS,
                         args_num=N,
                         x1_range=X1_RANGE,
                         x2_range=X2_RANGE,
                         precision=PRECISION,
                         population_size=POPULATION_SIZE,
                         type="min")
    opt_test.initPopulation()
    opt_test.optimize()
    print("best = ", opt_test.getBest().getTargetValue())