Esempio n. 1
0
def main():
    parser = OptionParser()

    parser.add_option("-n", "--ngram", dest="ngram",default="undefined")
    parser.add_option("-g", "--ga", dest="ga", type="int", default=800)

    (options, args) = parser.parse_args()

    ga.run(ngram_generate=(lambda: ngram.generate(options.ngram,TWELVE_BAR_BLUES)),num_iter=options.ga)
Esempio n. 2
0
def main():
    parser = OptionParser()

    parser.add_option("-n", "--ngram", dest="ngram", default="undefined")
    parser.add_option("-g", "--ga", dest="ga", type="int", default=800)

    (options, args) = parser.parse_args()

    ga.run(ngram_generate=(
        lambda: ngram.generate(options.ngram, TWELVE_BAR_BLUES)),
           num_iter=options.ga)
Esempio n. 3
0
def main():
    graph = data.generate()

    batches = [
        Batch(graph, ga.Params(200, 40, 0.4, 0.5, 0.1)),
        Batch(graph, ga.Params(500, 100, 0.4, 0.5, 0.1)),
        Batch(graph, ga.Params(1000, 200, 0.4, 0.5, 0.1)),
    ]

    for batch in tqdm(batches):
        graph = batch.graph
        params = batch.params

        params_hash = __batch_as_hash(params)

        logs_dir = LOGS.joinpath(params_hash)

        with Logger(logs_dir) as logger:
            ga_stats = ga.run(graph, params)

            worst = []
            mean = []
            best = []

            for epoch_stats in ga_stats:
                worst.append(np.min(epoch_stats.scores))
                mean.append(np.mean(epoch_stats.scores))
                best.append(np.max(epoch_stats.scores))

            summary = {}
            summary['worst'] = worst
            summary['mean'] = mean
            summary['best'] = best

            data_frame = pd.DataFrame.from_dict(summary)
            logger.save_csv(data_frame, 'summary')
            logger.add_entries(params.as_dict())
Esempio n. 4
0
    return sum


# Problem Definition
problem = structure()
problem.func = f
problem.nvar = len(cities)
problem.varmin = [c[1] for c in cities]
problem.varmax = [c[2] for c in cities]

# Parameters
params = structure()
params.maxit = 100
params.npop = 50
params.beta = 1
params.pc = 1
params.gamma = 0.1
params.mu = 0.01
params.sigma = 0.1

# Run GA
out = ga.run(problem, params, verbose=True)

# Results
print("\nBest Assignment:\n")
best_assignment = out.bestsol.assignment
for i in range(len(best_assignment)):
    print("\t {}: {}".format(cities[i][0], best_assignment[i]))
print("\nBest Reward: {}\n".format(out.bestsol.reward))
ga.plot(params.maxit, out.bestreward)
Esempio n. 5
0
                        [26, 11, 29, 25, 43, 0, 49, 30, 19, 30],
                        [44, 51, 45, 27, 10, 49, 0, 42, 48, 35],
                        [5, 22, 3, 36, 43, 30, 42, 0, 13, 6],
                        [8, 8, 11, 33, 46, 19, 48, 13, 0, 16],
                        [9, 23, 9, 32, 37, 30, 35, 6, 16, 0]]
    return cities


# Iniicializa a estrutura das cidades
cities = initialize()

# Parametros do algoritmo
config = structure()
#Tamanho da populacao
config.population_size = 20
# Numero de iteracoes que iram ser repetidas
config.number_iterations = 1000
# Probabilidade de ocorrer uma mutacao em um dado gene dos cromossomos filhos
# (0 a 100)
config.mutation_probability = 3
# Numero que representa o total de ocorrencias aleatorias que ocorreram durante
# a selecao de quem ira ou nao continuar na populacao
# Quanto maior for o valor, mais eventos aleatorios acontecerao  e em decorrencia
# disso mais aleatorio sera o resultado
# Quanto menor ele for definido maior sera as chances das novas populacoes serem
# escolhidas na selecao dos mais fortes e propensos a continuar a reproducao
config.cut_randomness = 30

#Inicia o GA
run(cities, config)
Esempio n. 6
0
# Variables according to problem definition
problem = structure()
problem.costfunc = function
problem.nvar = 30  #30 var
problem.varmin = -32  # -32
problem.varmax = 32  # 32

# GA parameters
params = structure()
params.maxit = 100000  # max iterations number
params.accep = 0.01  # acceptance for stop the alg
params.npop = 20  # population number
params.pc = 1  # variation initial population
params.gamma = 0.1  # crossover parameter
params.sigma = 0.3  # mutation parameter
params.mu = 0.03  # mutation % genes
params.beta = 1  # selection for the rolette wheel

#Run GA
output = ga.run(problem, params)

# Results
plt.plot(output.bestcost, 'b', linewidth=3)
plt.semilogy(output.bestcost)
plt.xlim(0, output.it)
plt.xlabel('Iterations')
plt.ylabel('Output')
plt.title('Genetic Algorithm (GA)')
plt.grid(True)
plt.show()
Esempio n. 7
0
    size_features: int = train_x.size(1)
    size_labels: int = int(train_y.max().item() - train_y.min().item()) + 1

    population, logbook = ga.run(
        x=train_x,
        y=train_y,
        list_sample_by_label=list_sample_by_label,
        ratio_min=RATIO_MIN,
        ratio_max=RATIO_MAX,
        population_size=GA_POPULATION_SIZE,
        selection_method=GA_SELECTION_METHOD,
        crossover_method=GA_CROSSOVER_METHOD,
        crossover_size=GA_CROSSOVER_SIZE,
        mutation_method=GA_MUTATION_METHOD,
        mutation_rate=GA_MUTATION_RATE,
        replacement_method=GA_REPLACEMENT_METHOD,
        num_generations=GA_NUM_GENERATIONS,
        checkpoint_dir=GA_CHECKPOINT_DIR,
        rand_seed=RAND_SEED,
        verbose=VERBOSE,
        classifier_num_hidden_layers=CLASSIFIER_NUM_HIDDEN_LAYERS,
        classifier_batch_size=CLASSIFIER_BATCH_SIZE,
        classifier_num_epochs=CLASSIFIER_NUM_EPOCHS,
        classifier_run_device=CLASSIFIER_RUN_DEVICE,
        classifier_learning_rate=CLASSIFIER_LEARNING_RATE,
        classifier_beta_1=CLASSIFIER_BETA_1,
        classifier_beta_2=CLASSIFIER_BETA_2)

    if GA_CHECKPOINT_DIR is not None:
        with open(os.path.join(GA_CHECKPOINT_DIR, "logbook.pkl"),
                  mode="wb") as fp:
Esempio n. 8
0
params.npop = 50
params.beta = 1
params.pc = 1
params.gamma = pC
## mutation parameters
params.mu = pM
params.sigma = 0.1

x = 0
max = []
min = []
avg = []

while x < trial_count:
    #Run GA
    out = ga.run(problem, params, "classic")
    max.append(np.max(out.bestcost))
    min.append(np.min(out.worstcost))
    avg.append(sum(out.bestcost) / len(out.bestcost))
    print("Run " + str(x + 1) + " done")
    x += 1

print("Max: " + str(np.max(max)))
print("Min: " + str(np.min(min)))
print("Average: " + str(sum(avg) / trial_count))

print(out.bestsol)
ChordProgToPic(out.bestsol)
midi.run(out.bestsol)

#play midi output
Esempio n. 9
0
for x in range(15):
    t = ga.DNAbase()
    population.append(t)
ga = ga.GA(population, 1, eval_fun)
ga.ini()
plt.scatter([para_2_x(x.para[0]) for x in ga.population],
            [x.score for x in ga.population],
            c=(1, 1, 0),
            s=50,
            marker='*')
for x in range(7):
    #fig=plt.figure()
    #plt.subplot(111,axisbg=(0.5,0.5,0.5))
    #plt.plot([x/10.0 for x in img_x],img_y,label="$xsin(3x)$",color=(1,0,0),linewidth=1)
    #plt.scatter([para_2_x(x.para[0]) for x in ga.population],[x.score for x in ga.population],c=(1,1,0),s=50,marker='*')
    ga.run()
    print(x, end='	')  #代数
    for y in ga.population:
        print('%.3f' % y.score, end=',[')
        for z in y.para:
            print('%.2f' % para_2_x(z), end=',')
        print('],', end='')
    print()
    #tmp=0
    #for x in ga.population:
    #tmp+=1
    #xx=[para_2_x(y[0][0]) for y in x.test_rec]
    #yy=[y[1] for y in x.test_rec]
    #print(xx,yy)
    #print(len(xx))
    #color=((tmp & 0x04)>>2,(tmp & 2)>>1,tmp & 1)
Esempio n. 10
0
import ga

if __name__ == '__main__':
    POPULATION_SIZE = 5
    MAX_ITER = 10
    MUTATION_PROB = 10
    ga.run(POPULATION_SIZE, MAX_ITER, MUTATION_PROB)