コード例 #1
0
ファイル: Main.py プロジェクト: danielkonecny/bin-project
def evolve_model(evolve_population_size=10,
                 evolve_recombinate_count=5,
                 evolve_generation_count=10):
    evolution = Evolution.Evolution()
    evolution.init_population(evolve_population_size)
    evolution.evaluate_population()
    print(f"Original population: {evolution.population}")
    print(f"Original evaluation: {evolution.evaluation}")

    for generation in range(evolve_generation_count):
        offsprings = []
        for recombinate_index in range(evolve_recombinate_count):
            parent1, parent2 = evolution.get_parents()
            offspring1, offspring2 = evolution.recombinate(parent1, parent2)
            size1 = Evolution.get_model_encoding(offspring1)
            if size1 < 32 * 32:
                print(
                    f"New individual obtained by recombination with size {size1} - {offspring1}."
                )
                offsprings.append(offspring1)
            size2 = Evolution.get_model_encoding(offspring2)
            if size2 < 32 * 32:
                print(
                    f"New individual obtained by recombination with size {size2} - {offspring2}."
                )
                offsprings.append(offspring2)

        mutated = Evolution.mutate(offsprings)
        evolution.combine_generations(mutated)
        evolution.set_new_population()

    evolved_autoencoder = evolution.get_best_individual()

    return evolved_autoencoder
コード例 #2
0
def get_output(probability):
    feature_name = probability_selector(probability)
    input_init = inputs.Input(probability, feature_name=feature_name)
    duration = input_init.get_duration()
    input_init.delete_duration()
    input_init.normalize()
    tra_feature, tra_label, vaildation_feature, vaildation_label, test_feature, test_label = input_init.data_generator(
    )
    vaild_list = input_init.vaild_list
    vaild_dur = []
    for vaild_num in vaild_list:
        vaild_dur.append(duration[vaild_num])

    optimal_net = ep.evolve(30,
                            1,
                            tra_feature,
                            tra_label,
                            vaildation_feature,
                            vaildation_label,
                            test_feature,
                            test_label,
                            type='random')
    w, b, e, r, predict, test = ep.Evolution().network_optimizer(tra_feature,
                                                                 tra_label,
                                                                 test_feature,
                                                                 test_label,
                                                                 optimal_net,
                                                                 18600,
                                                                 final=True)
    print(vaild_dur)
    return e, predict, test, vaild_dur
コード例 #3
0
        def runModel():
            allCP = int(AllCEntry.get())
            allDP = int(AllDEntry.get())
            TFTP = int(TFTEntry.get())
            numOfTournaments = int(numofTEntry.get())

            allC = Agent(1, 1, 1, "All-C")
            allD = Agent(0, 0, 0, "All-D")
            TFT = Agent(1, 1, 0, "T-F-T")

            testPopulation = [{
                "agent": allC,
                "count": allCP
            }, {
                "agent": TFT,
                "count": TFTP
            }, {
                "agent": allD,
                "count": allDP
            }]
            evolution = Evolution(allCP, allDP, TFTP)
            tempAgentCounts = evolution.run(testPopulation, numOfTournaments)

            for n in range(0, numOfTournaments + 1):

                lineDataC.set_xdata(evolution.round_history[0:n + 1])
                lineDataC.set_ydata(evolution.C_history[0:n + 1])

                lineDataD.set_xdata(evolution.round_history[0:n + 1])
                lineDataD.set_ydata(evolution.D_history[0:n + 1])

                lineDataTFT.set_xdata(evolution.round_history[0:n + 1])
                lineDataTFT.set_ydata(evolution.TFT_history[0:n + 1])

                # also points!
                axes.plot(evolution.round_history[n - 1],
                          evolution.C_history[n - 1],
                          color="red",
                          marker="o")
                axes.plot(evolution.round_history[n - 1],
                          evolution.D_history[n - 1],
                          color="blue",
                          marker="o")
                axes.plot(evolution.round_history[n - 1],
                          evolution.TFT_history[n - 1],
                          color="green",
                          marker="o")

                canvas.draw()
コード例 #4
0
def main () : 

    population_size = 100

    N = 10
    k = 6
    p = 0.99

    lamda = [0,1,1]

    number_of_neighbors = 25

    number_of_generation = 100
    mut_prob = 1./N
 
    seed = 1000   
    

    landscape = Landscape.Landscape(N,k,seed,p) 
    evolution = Evolution.Evolution(landscape,population_size, 1, number_of_neighbors,Archive.Archive(10,""), N) 
    mth = ["None","N","R"]
    for i in range(3): 
        print " ====================================================================="
        archive =  Archive.Archive(10,mth[i]) 
        evolution.archiving = archive
        #evolution.lamda = lamda[i]
        
        history  = evolution.run(number_of_generation,mut_prob)
        maxs = [ ]
        for gen in history : 
            values = [genotype.fitness for genotype in gen]
            maxs.append(numpy.max(values))
        plt.plot(maxs, label=r"$method = $" +str(mth[i]))
        
    
    plt.xlabel("Generation")
    plt.ylabel("Max Fitness")

    plt.title("Novelty Vs Fitness")
    plt.legend(loc="lower right", shadow=True, fontsize='12')
    plt.show()
コード例 #5
0
def compare(n):
    t = time.time()
    #generte the BinImages from the same random image
    im2 = gen2.randomImage(n)
    im1 = Image1.BinImage(deepcopy(im2.image), False, True)

    evol1 = Evol1.Evolution(im1)
    evol2 = Evol2.Evolution(im2)

    t1 = time.time()
    print("\ngeneration of an image with ", n, " pixels : ", t1 - t,
          " seconds")

    algo1.algo1(evol1)
    t2 = time.time()
    print("first algorithm : ", (t2 - t1), " seconds")
    print("                  ", (evol1.getNbActions()), " actions")

    algo2.algoB4W8(evol2)
    print("second algorithm : ", (time.time() - t2), " seconds")
    print("                   ", (evol2.getNbActions()), " actions")

    return (evol1.getNbActions(), evol2.getNbActions())
コード例 #6
0
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 29 21:27:45 2016

@author: Alon
"""

import Evolution as Evo

Ev = Evo.Evolution(usePrints=True, populationSize=30, numOfEvolutionSteps=10)
Ev.run()
コード例 #7
0
# -*- coding: utf-8 -*-
"""
Created on Wed Mar  1 12:56:34 2017

@author: Alon
"""
import DNAexample as dna
import Evolution as Evo

Ev = Evo.Evolution(dna,usePrints=True,populationSize=20,numOfEvolutionSteps=100)
Ev.run()
コード例 #8
0
from Evolution import *

e = Evolution()
e.iniExperiment()
コード例 #9
0
from Tools import *
from Scenario import *
from NSGA import *
from Evolution import *
import matplotlib.pyplot as plt

tool_box = Tools()
flow_data = tool_box.read_flow_data_from_txt()
loc_data = tool_box.read_loc_data_from_txt()
time_data = tool_box.read_slot_data_from_txt()
scenario = Scenario(flow_data, loc_data, time_data)
# scenario.generate_initial_solution()
print 'scenario generated'
problem = NSGA_problem(scenario)
evolve = Evolution(problem, 50, 100)
selected_individuals = evolve.evolve()
f = open('gene.txt', 'w')
for i in selected_individuals:
    s = ''
    for g in i.features:
        s = s + ',' + str(g)
    f.write(s + '\n')
f.close()
x = [problem.f1(i) for i in selected_individuals]
y = [problem.f2(i) for i in selected_individuals]
print x, y
plt.plot(x, y, 'ro')
plt.show()
コード例 #10
0
ファイル: Main.py プロジェクト: EivMeyer/python_ts_genprog
if (__name__ == '__main__'):
    parser = argparse.ArgumentParser(description='Genetic programming engine')
    parser.add_argument(
        '-test',
        dest='should_test',
        help='Predict single test sample using defined predictor function',
        action='store_true')
    args = parser.parse_args()

    root = os.path.dirname(os.path.realpath(__file__))
    config = Config.Configuration()
    reset_storage(root)

    #X_train, y_train, X_val, y_val = Datasets.load(name = 'Random_Walk_With_Mommentum', config = config, root = root)
    #X_train, y_train, X_val, y_val = Datasets.load(name = 'Bitcoin_USD', config = config, root = root)
    X_train, y_train, X_val, y_val = Datasets.load(
        name='North_Carolina_Weather', config=config, root=root)

    if (args.should_test):
        print(' & '.join(['{:<.2f}'.format(x[0])
                          for x in X_train[0].tolist()]))
        print(X_train[0], y_train[0], test_predict(X_train[0],
                                                   len(X_train[0])))
        exit(0)

    evolution = Evolution.Evolution(root=root,
                                    config=config,
                                    X_train=X_train,
                                    y_train=y_train,
                                    X_val=X_val,
                                    y_val=y_val)
コード例 #11
0
def preprocessing_data(x):
    avg = np.average(x, axis=0)
    m = np.min(x, axis=0)
    M = np.max(x, axis=0)
    return [avg, avg - m, M - avg]


exp_h_fmax = []
exp_h_favg = []
exp_h_div = []

if __name__ == '__main__':
    fp = open("checkpoint.txt", "w+")  #file pointer
    for e in range(config.NUMBER_OF_EXPERIMENTS):
        ea = Evolution(nn_layer)
        ea.evolution(verbose=False, exp=e, fp=fp)
        exp_h_fmax.append(ea.h_fmax)
        exp_h_favg.append(ea.h_favg)
        exp_h_div.append(ea.h_div)
        print('Experiment %d done' % (e))

    fp.close()
    x = np.arange(ea.num_gen)

    exp_h_fmax = preprocessing_data(exp_h_fmax)
    y = exp_h_fmax[0].tolist()
    yl = exp_h_fmax[1].tolist()
    yh = exp_h_fmax[2].tolist()
    plt.figure()
    plt.title('Max Fit')
コード例 #12
0
#print(evol.getNbActions())


"""
#%% analyse complexité

nbIter = 3
ns = [5,10,20,30,50,65]
value = []

for n in ns :
	listOfValues = []
	for i in range(nbIter) :
		print("generating...")
		image = generation.randomImage(n)
		evol = Evolution.Evolution(image)
		print("solving")
		algo1(evol)
		listOfValues.append(evol.getNbActions())
		print(n, " pixels : ", evol.getNbActions(), " actions.\n")
	value.append(sum(listOfValues) / nbIter)

plt.figure()

plt.xlabel('nb of pixels')
plt.ylabel('nb of exchanges')
plt.title('complexity of the first algorithm') 

plt.plot(ns, value)
plt.show()
コード例 #13
0
def main():
    a = Evolution(False)
    a.Calculate()
コード例 #14
0
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 15:11:51 2020

@author: nbarl
"""

import BinImage
import Evolution
from generation import randomImage
from algo2 import findP, B4W8kinterchange, algoB4W8





image_test = [[0,0,0,0],
			  [0,0,0,0],
			  [0,1,1,0]]


#im = BinImage.BinImage(image_test, False, True)
im = randomImage(40)
evol = Evolution.Evolution(im)

algoB4W8(evol)

evol.createGif("B4W8.gif", 100)
print(evol.getNbActions())