train = False env = gym.make("gym-snake-v0") # env = ObservationWrapper(env) env.set_params( reward=(0, 0, 1, -1), obs="simple", size=15, termination=75, spawn="random", add_len=1, start_length=3, ) model = nn.Sequential(nn.Linear(10, 24, bias=False), nn.ReLU(), nn.Linear(24, 4, bias=False)) if train: r = ContinuousRepresentation(-1, 1, getNumWeights(model)) ga = GA(r, lambda x: objective(env, model, x), debug=1) ga.initPopulation(300) ga.evolve(400) best_weights = ga.getSolution()[1] for i in range(5): objective(env, model, best_weights, render=True) # save model np.save("experiments/GA/weights_2layer.npy", best_weights) else: weights = np.load("experiments/GA/weights_2layer.npy") for i in range(10): objective(env, model, weights, render=True)
import matplotlib.pyplot as plt import numpy as np from GA import GA from TSP import TSP N_CITIES = 20 # DNA size CROSS_RATE = 0.1 MUTATE_RATE = 0.02 POP_SIZE = 500 N_GENERATIONS = 500 ga = GA(DNA_size=N_CITIES, pcross=CROSS_RATE, pmutation=MUTATE_RATE, pop_size=POP_SIZE) env = TSP(N_CITIES) for gen in range(N_GENERATIONS): lx, ly = ga.translateDNA(ga.pop, env.city_position) fitness, total_distance = ga.get_fitness(lx, ly) ga.evolve(fitness) best_idx = np.argmax(fitness) #返回最大值的索引 print( 'Gen:', gen, '| best fit: %.2f' % fitness[best_idx], ) env.plotting(lx[best_idx], ly[best_idx], total_distance[best_idx]) #绘制出每一代的最优路径 plt.ioff() plt.show()
if loadit: docs = pickle.load(open('docs.pkl', 'rb')) else: data_path = '../data/github_issues.csv' df = pd.read_csv(data_path) docs = Documents() # docs.load(list(df['description'])[:300]) docs.load(list(df['description'])) docs.vectorise() pickle.dump(docs, open('docs.pkl', 'wb+')) print("No. of documents loaded: {}".format(docs.get_doc_size())) corpus = docs.get_vectors() dictionary = docs.get_dictionary() GA = GA(corpus, dictionary, pop_size=30, fitness_budget=10000, objective='coherence') GA.initialise_population() GA.evolve() fittest_gene = GA.get_fittest() # model = GA.get_model() # docs.assign_labels(model) print('Fittest Gene discovered {} topics with score of {:.8f}'.format( fittest_gene.n, GA.fitness))
# Start of GA configuration ga = GA(Population_size, Chromosome_length, True) # Set the GA Configuration ga.initialization_impl = RandomInitialization() ga.mutation_impl = PerGeneMutation(Mutation_rate) ga.selection_impl = TournamentSelection() ga.crossover_impl = FastSinglePointCrossover() ga.termination_impl = GenerationTermination(Total_generations) # ga.evaluation_impl = SumOfDiffEvaluation2(60) ga.evaluation_impl = TestEvaluation() ga.initialize() while not ga.is_over(): ga.evolve() best = ga.get_best() print("Curent Trial " + str(Current_trial)) print("Generation #" + str(ga.generation)) print("\tBest Fitness = " + str(best[1])) # ---------- Each Chromosome ---------- # for i in range(len(ga.population)): chromosome = ga.population[i] # Get the fitness of the current chromosome fitness = ga.get_fitness(chromosome) # Add to Database list chromosome_string = ' '.join(map(str, chromosome)) # Print Chromosome - Fitness print("\t" + str(ga.population[i]) + " - " + str(ga.get_fitness(ga.population[i])))