Esempio n. 1
0
    def predict_tablature(self, mode = 'FromAnnos'):
        '''mode --> {From_Annos, FromCNN} first reads 
        from annotations onset-pitch second estimates'''
        strings = []
        if mode == 'FromCNN':
            onsets, midi_notes = self.predict_notes_onsets()
            self.temp_tablature = Tablature(onsets, midi_notes, [])
            estim_tab, probs = self.rnn_predict_strings()
            temp = [(x[1],1) for x in estim_tab]
            self.rnn_tablature_FromCNN = Tablature(onsets, midi_notes, temp)
            fin_tab, gen = genetic(estim_tab, probs, coeff)
            for s in fin_tab:
                strings.append((s[1],1))
            self.predicted_tablature_FromCNN = Tablature(onsets, midi_notes, strings)

        elif mode == 'FromAnnos':
            self.temp_tablature = self.true_tablature
            estim_tab, probs = self.rnn_predict_strings()
            string_temp = [(x[1],max(p)) for x,p in zip(estim_tab,probs)]
            onset_temp = [(x[-2],1) for x in estim_tab]
            midi_temp = [(x[0],1) for x in estim_tab]
            self.rnn_tablature_FromAnnos = Tablature(onset_temp, midi_temp, string_temp)
            fin_tab, gen = genetic(estim_tab, probs, coeff)
            for s in fin_tab:
                strings.append((s[1],1))
            self.predicted_tablature_FromAnnos = Tablature(onset_temp, midi_temp, strings)
Esempio n. 2
0
def main():
    im = Image.open(filename)
    im.load()
    im_gray = im.convert('L')  # translate to  gray map
    genrtic = genetic(im_gray)
    best_threshold = genrtic.get_threshold()  #最佳切割阈值
    threshold(best_threshold, im_gray)
Esempio n. 3
0
def cv(results):
    for file_loc in glob.glob("DATA/Atlanta.tsp"):
        print(file_loc)
        for p in range(100, 1000, 150):
            for e in range(0, 20, 5):
                #for m in range(0,20,5):
                for m in range(1):
                    m = 20
                    local_time = 0
                    local_qual = 0
                    for i in range(trials):
                        start_time = time.time()
                        random.seed(options["seed"])
                        params, cities = read_file(file_loc)
                        g = genetic.genetic(params,
                                            cities,
                                            options["cutoff"],
                                            pop=p,
                                            elite=e / 100,
                                            mutate=m / 100)
                        trace, quality, route = g.evolve()
                        local_time = local_time + trace[-1][0]
                        local_qual = local_qual + quality
                    results.append([
                        p, e / 100, m / 100, local_time / trials,
                        local_qual / trials
                    ])
                    print(results)
Esempio n. 4
0
def create_brain(network_params, fitness, evaluations):
    network = Network(NeuralBee.network_input_size(), network_params.hidden_neurons, network_params.outputs)
    
    def get_network_with(args):
        network.set_params(args)
        return network
    
    best_params = genetic(lambda x: fitness(get_network_with(x)), network.number_of_params())
    return get_network_with(best_params)
Esempio n. 5
0
def qrtd2(results2):
    for file_loc in ["DATA/NYC.tsp"]:
        for i in range(trials):
            temp = []
            start_time = time.time()
            random.seed(options["seed"])
            params, cities = read_file(file_loc)
            g = genetic.genetic(params, cities, 125)
            trace, quality, route = g.evolve()
            results2.append([quality])
            print(results2)
Esempio n. 6
0
def main():
    # Create Graph Colouring Problem
    problem = GraphColouring()
    # Catch Initial Graph
    graph_structure = problem.get_initial_graph()
    # Calculate edges number from graph structure
    # edges number will be needed in evaluating graph state
    edges_number = 0
    for x in graph_structure:
        edges_number += len(x.neighbours)
    edges_number /= 2
    # Create Initial State with structure and edges number
    initial_state = State(graph_structure=graph_structure,
                          edges_number=edges_number)
    # Perform Algorithms :
    algorithm = "GENETIC"
    if algorithm == "SIMPLE HILL CLIMBING":
        simple_hill_climbing(initial_state)

    if algorithm == "STOCHASTIC HILL CLIMBING":
        stochastic_hill_climbing(initial_state)

    if algorithm == "FIRST CHOICE HILL CLIMBING":
        first_choice_hill_climbing(initial_state)

    if algorithm == "RANDOM RESTART HILL CLIMBING":
        random_restart_hill_climbing(initial_state)

    if algorithm == "SIMULATED ANNEALING":
        simulated_annealing(initial_state=initial_state)

    if algorithm == "GENETIC":
        number_of_generations = 5000
        population_size = 100
        tournament_size = 5
        mutation_rate = 0.05
        genetic(initial_state=initial_state,
                number_of_generations=number_of_generations,
                population_size=population_size,
                tournament_size=tournament_size,
                mutation_rate=mutation_rate)
Esempio n. 7
0
def runtime(results):
    for file_loc in glob.glob("DATA/*.tsp"):
        print(file_loc)
        local_time = 0
        local_qual = 0
        for i in range(trials):
            start_time = time.time()
            random.seed(options["seed"])
            params, cities = read_file(file_loc)
            g = genetic.genetic(params, cities, options["cutoff"])
            trace, quality, route = g.evolve()
            local_time = local_time + trace[-1][0]
            local_qual = local_qual + quality
        results.append([
            file_loc.strip("DATA/"), local_time / trials, local_qual / trials
        ])
        print(results)
Esempio n. 8
0
def main():
    A = DataStructuur("voorbeeld.csv")

    # probeer verschillende algoritmes
    # brute force
    B = randomize(A)

    # iteratief
    C = hill_climber(A)

    # constructief
    D = breadth_first(A)

    # evolutionair
    E = genetic(A)

    print("score van random:                {}\n"
          "score van hill_climber:          {}\n"
          "score van breadth_first:         {}\n"
          "score van genetisch algoritme1:  {}\n".format(
              score(B), score(C), score(D), score(E)))
Esempio n. 9
0
    def __init__(self, parent_1=None, parent_2=None):
        """
        Inits an individual.
        If it has parents, generate its genes via crossover operation.
        If not, generate its genes randomly.

        Args:
            parent_1: a parent.
            parent_2: another parent.
        """
        self.genes = []
        op = genetic()
        if parent_1 and parent_2:
            array = op.crossover3(parent_1, parent_2, TRI_NUM)
            self.generate_genes_from_array_with_mut(array, MUT_RATE)
        else:
            for i in xrange(TRI_NUM):
                self.genes.append(gene())
        # set actual image
        self.im = self.get_current_img()
        # calculate fitness
        self.fitness = self.get_fitness(TARGET)
Esempio n. 10
0
    def __init__(self, parent_1=None, parent_2=None):
        """
        Inits an individual.
        If it has parents, generate its genes via crossover operation.
        If not, generate its genes randomly.

        Args:
            parent_1: a parent.
            parent_2: another parent.
        """
        self.genes = []
        op = genetic()
        if parent_1 and parent_2:
            array = op.crossover3(parent_1, parent_2, TRI_NUM)
            self.generate_genes_from_array_with_mut(array, MUT_RATE)
        else:
            for i in xrange(TRI_NUM):
                self.genes.append(gene())
        # set actual image
        self.im = self.get_current_img()
        # calculate fitness
        self.fitness = self.get_fitness(TARGET)
Esempio n. 11
0
results = []

#for learning_rate in parameters.gradient_descent['learning_rate']:
#    for regularization_strength in parameters.gradient_descent['regularization_strength']:
#        train_loss, test_loss, hyperparameters = gradient_descent({'learning_rate': learning_rate, 'regularization_strength': regularization_strength, 'num_iterations': parameters.gradient_descent['num_iterations']})

for mutation_amplitude in parameters.genetic['mutation_amplitude']:
    for regularization_strength in parameters.genetic[
            'regularization_strength']:
        train_loss, test_loss, hyperparameters = genetic({
            'mutation_amplitude':
            mutation_amplitude,
            'regularization_strength':
            regularization_strength,
            'num_chromosomes':
            parameters.genetic['num_chromosomes'],
            'num_generations':
            parameters.genetic['num_generations'],
            'parent_proportion':
            parameters.genetic['parent_proportion'],
            'random_gene_amplitude':
            parameters.genetic['random_gene_amplitude']
        })

        results.append({
            'train_loss': train_loss,
            'test_loss': test_loss,
            'last_test_loss': test_loss[-1],
            'hyperparameters': hyperparameters
        })

results = sorted(results, key=lambda k: k['last_test_loss'])
Esempio n. 12
0
for i in range(0, 25):
    prob.append(0.1)

for i in range(25, MAX_LENGHT):
    prob.append(0.5)

for i in range(0, 8):
    conjunto.append(choices(population=estant, k=randint(3, 7), weights=prob))

print(conjunto)

start = []
for i in range(0, N_POB):
    start.append(generate_ind())

best, history = genetic(start, conjunto, hist=True)
print(best)
print("DONE")

with open('../tests/fitness-test.csv', mode='w') as temp_file:
    writer = csv.writer(temp_file, quoting=csv.QUOTE_NONE)

    writer.writerow(['GEN', 'fitness'])

    for i in range(0, N_POB):
        writer.writerow([i, history[i]])

cost0 = []
cost1 = []

for orden in conjunto:
                r = r + 1
            if ((r % 2) == 0):
                new.append((node1.state)[i])

            else:
                new.append((node2.state)[i])

        y = node(new, None, 1)

        return y

    def mutation(self, node1):
        p = (1 / (self.number * 40))
        a = []
        for i in range(0, self.number):
            a.append((node1.state)[i])
        for i in range(0, self.number):
            ran = random.uniform(0, 1)
            if (ran < (1 / p)):
                if (a[i] == 0):
                    a[i] = 1
                else:
                    a[i] = 0
        y = node(a, None, 1)
        return y


x = p2()

genetic.genetic(x)
Esempio n. 14
0
    plt.plot(numbers, excess)

    plt.show()


if __name__ == '__main__':
    Tests = TestList()
    Tests.testCreater("CSE624TESTSET.txt")
    x = 0
    numbers = []
    tabutimes = []
    genetictimes = []
    excessDifference = []
    while (x < 100):

        resultGenetic = genetic(Tests.listOfTests[x])
        print("Genetic Way -------- Test Case " + str(x) + ": " +
              explainBinary(resultGenetic[0]) + " with excess of " +
              str(resultGenetic[1]))

        #resultTabu=tabu(Tests.listOfTests[x])

        #print("Tabu Way -------- Test Case "+str(x)+": "+explainBinary(resultTabu[0])+ " with excess of " + str(resultTabu[1]))

        #resultGreedy=greedy(Tests.listOfTests[x])
        #print("Greedy Way --------- Test Case "+str(x)+": "+resultGreedy[0]+str(resultGreedy[1]))

        #resultBranch=branchandbound(Tests.listOfTests[x])
        #print("BranchAndBound Way - Test Case "+str(x)+": "+explainBinary(resultBranch[1])+ " with excess of " + str(-1*resultBranch[3]) )

        #resultSimulated=simulatedannealing(Tests.listOfTests[x])
Esempio n. 15
0
                    default=100,
                    help="Population of genepool")
parser.add_argument("-e",
                    "--elite",
                    type=float,
                    default=0.2,
                    help="Elitism factor")
parser.add_argument("-m",
                    "--mutate",
                    type=float,
                    default=0.2,
                    help="Probability of mutation")
parser.add_argument("-s",
                    "--silent",
                    type=bool,
                    default=False,
                    help="True if no visualization needed")
args = parser.parse_args()

# Step 1 - Convert STL file to pointcloud (simulates 3D printer)
pointcloud = pc.convert(args.filename, args.points)

# Step 2 - Use Genetic Algorithm to transform pointcloud to array of Bezier control points
opt = genetic.genetic(pointcloud, args.N, args.cutoff, args.gen, args.pop,
                      args.elite, args.mutate)
cp = opt.evolve()

# Step 3 - Visualize Bezier surface
if not args.silent:
    vis.plot(cp)
Esempio n. 16
0
    greedyResult = max(sum_array)



    #Compare results.

    print ("\noptimum result")
    print(optimumResult )
    print ("\ngreedy result")
    print(greedyResult)

    # execute genetic algorithm
    array_after_genetic = []
    sum_array= []
<<<<<<< HEAD
    array_after_genetic = genetic.genetic(array_of_processors, 3, optimumResult)  #Drugi parametr to ilo sekund.
=======
    array_after_genetic = genetic.genetic(array_of_processors, 2)  #Drugi parametr to ilość sekund.

>>>>>>> cd61ee90b019bf5b38aef51a6b47dc9906318a6d
    for i in range(processorsNumber):
        sum_array.append(sum(array_after_genetic[i]))
    print( "wynik po genetycznym")
    print (max(sum_array))

<<<<<<< HEAD
    #DO usuniecia
=======
    for i in range(len(array_after_genetic)):
        print(sorted(array_after_genetic[i], reverse=True), sum(array_after_genetic[i]))
Esempio n. 17
0
def solve(jobs):
    times_list = list(map(lambda job: job['times'], jobs['jobs']))
    scheduled_times = genetic(times_list)
    scheduled_jobs = [jobs['jobs'][i - 1] for i in scheduled_times]
    return {'jobs': scheduled_jobs}
Esempio n. 18
0
    branch.main()
    quality = branch.minimum
    route = branch.bestSolution
    trace = branch.trace

elif options.method == "Approx":
    trace, quality, route = construction_heuristic.nearest_neighbor(
        params, cities, options.cutoff)
elif options.method == "LS1":
    s = SA.SimulatedAnnealing(
        cities,
        0.00001)  # the second argument is the cooling rate, default is 0.001.
    s.anneal(options.cutoff)
    quality = s.best_distance
    route = s.best_route
    trace = s.trace
elif options.method == "LS2":
    g = genetic.genetic(params, cities, options.cutoff)
    trace, quality, route = g.evolve()

#### ########## ####

print(quality)
for id in route:
    print(id, end=" ")
print("")

write(trace, quality, route, params, options)

######## ############## ########
Esempio n. 19
0
                greedy_solution = greedy(storage)

            if startswith in skip_genetic:
                solution = greedy_solution
            else:
                # injecting greedy solution to initial population of genetic algorithm
                _injections = ceil(params["pop_size"] * injection_multiplier)
                greedy_injection = [
                    copy(greedy_solution) for _ in range(_injections)
                ]

                solution = genetic(
                    storage,
                    params["no_generations"],
                    params["pop_size"],
                    elite,
                    mutation_prob,
                    no_mutations,
                    greedy_injection,
                )

            fitness([greedy_solution], storage)
            # print(f"{FILE} [greedy] score: {greedy_solution.score}")
        else:
            solution = genetic(
                storage,
                params["no_generations"],
                params["pop_size"],
                elite,
                mutation_prob,
                no_mutations,
Esempio n. 20
0
    fig.savefig("test.png")


l = 0.35
D = np.array([5, 10, 15, 20])
for m in (1, 4):
    greedyData = []
    geneticData = []
    naiveData = []
    for d in D:
        if l < 0.40:
            n = naive(data.get(l, m, delai=d))
            naiveData += [n]
        g = greedy(data.get(l, m, delai=d))
        greedyData += [g]
        ge = genetic(data.get(l, m, delai=d))
        geneticData += [ge]

    naiveData = np.array(naiveData)
    greedyData = np.array(greedyData)
    geneticData = np.array(geneticData)

    fig, ax = plt.subplots()
    ax.plot(D[:len(naiveData)], naiveData[:, 0], label='Naive')
    ax.plot(D[:len(greedyData)], greedyData[:, 0], label='Glouton')
    ax.plot(D[:len(geneticData)], geneticData[:, 0], label="Génétique")
    ax.set(xlabel='Le delai maximum [time slot]',
           ylabel='énergie [J]',
           title="Consommation d'énergie vs Le delai")
    legend = ax.legend(loc='upper left', shadow=True, fontsize='x-large')
    save(fig, f'EvsD{m}', "eps")
Esempio n. 21
0


print("Simulated annealing:")
arr2 = copy.deepcopy(arr)
anneal = FourPeaksAnneal(arr2, fitness)
opt_arr, opt_fit = anneal.anneal()
print(opt_arr)
print(opt_fit)

arr = [0 for i in range(l)]
for i in range(2, l, 2):
    arr[i] = 1

print("Hill climbing")
arr2 = copy.deepcopy(arr)
opt_arr, opt_fit = climb(arr2, fitness)
print(opt_arr)
print(opt_fit)

arr = [0 for i in range(l)]
for i in range(2, l, 2):
    arr[i] = 1

print("Genetic algo:")
arr2 = copy.deepcopy(arr)
opt_arr, opt_fit = genetic(arr2, fitness_gen)
print(convert(opt_arr))
print(opt_fit)

Esempio n. 22
0
File: nn.py Progetto: arvindr9/ml
test_anneal = []

clf.coefs_ = []
clf.intercepts_ = []
#anneal(clf, hid_layers, x_train, y_train) #uses simulated annealing to find the optimal weights
anneal = NNAnneal(clf, hid_layers, x_train, y_train)
([clf.coefs_, clf.intercepts_]), e = anneal.anneal()

print(accuracy_score(clf.predict(x_train), y_train))
print(accuracy_score(clf.predict(x_val), y_val))
print(accuracy_score(clf.predict(x_test), y_test))
# acc_anneal.append(accuracy_score(clf.predict(x_val), y_val))
# test_anneal.append(accuracy_score(clf.predict(x_test), y_test))

# print(acc_anneal)
# print(test_anneal)

print("Hill climbing:")
clf.coefs_ = []
clf.intercepts_ = []

climb(clf, hid_layers, x_train, y_train)
print(accuracy_score(clf.predict(x_train), y_train))
print(accuracy_score(clf.predict(x_val), y_val))
print(accuracy_score(clf.predict(x_test), y_test))

print("Genetic algorithm:")
clf.coefs_ = []
clf.intercepts_ = []
genetic(clf, hid_layers, x_train, y_train)
Esempio n. 23
0
        arr2.append(int(round(i)))
    return arr2


def fitness_gen(arr):
    return fitness(convert(arr))


print("Simulated annealing:")
edges2 = copy.deepcopy(edges)
colors2 = copy.deepcopy(colors)
anneal = KColorAnneal(colors2, k, edges2, fitness)
anneal.steps = 5000
opt_colors, opt_fit = anneal.anneal()
print(opt_colors)
print(opt_fit)

print("Hill climbing:")
edges2 = copy.deepcopy(edges)
colors2 = copy.deepcopy(colors)
opt_colors, opt_fit = climb(colors2, k, edges2, fitness)
print(opt_colors)
print(opt_fit)

print("Genetic algo:")
edges2 = copy.deepcopy(edges)
colors2 = copy.deepcopy(colors)
opt_colors, opt_fit = genetic(colors2, k, fitness_gen)
print(convert(opt_colors))
print(opt_fit)
Esempio n. 24
0
# menampilkan algoritma yg akan digunakan
print ("Daftar algoritma:")
print ("1 : Hill Climbing")
print ("2 : Simulated Annealing")
print ("3 : Genetic Algoritthm")

# menerima masukan algoritma yg akan digunakan 
nama = int(input("Algoritma yang akan digunakan : "))

print("\nSOAL:")
soal = help.getListRandomized()
help.printResult(soal)
print (help.totalConflictSesama(soal), help.totalConflictLawan(soal))

print("\nJAWABAN:")

answer = []
if nama == 1:
	answer = hill(soal, 1000)
elif nama == 2:
	answer = annealing(soal, 10000, 100, 5)
elif nama == 3:
	answer = genetic()

help.printResult(answer)

result = []
result = help.totalConflict(answer)
print (result[0], result[1])
Esempio n. 25
0
l = 0.45

lam = np.arange(0.25, 3.001, 0.20)
lam = np.insert(lam, 1, [0.30, 0.35])

for m in (1, 4):
    greedyData = []
    geneticData = []
    naiveData = []
    for l in lam:
        if l < 0.40:
            n = naive(data.get(l))
            naiveData += [n]
        g = greedy(data.get(l, m))
        greedyData += [g]
        ge = genetic(data.get(l, m))
        geneticData += [ge]
        # print(g)
        # print(ge)

    naiveData = np.array(naiveData)
    greedyData = np.array(greedyData)
    geneticData = np.array(geneticData)

    # Energie vs Lambda
    fig, ax = plt.subplots()
    ax.plot(lam[:len(naiveData)], naiveData[:, 0], label='Naive')
    ax.plot(lam[:len(greedyData)], greedyData[:, 0], label='Glouton')
    ax.plot(lam[:len(geneticData)], geneticData[:, 0], label="Génétique")
    ax.set(xlabel='La charge du système [requetes / time slot]',
           ylabel='énergie [J]',
Esempio n. 26
0
import random
random.seed(33)

from genetic import genetic

if __name__ == "__main__":
    best_result = genetic()
    
    for index, move in enumerate(best_result):
        print "Move", 1+index
        for feature, function in move.iteritems():
            print "\t",feature, "=", function
            
Esempio n. 27
0
                                                      generations, iterations)
        writefile = open(sys.argv[3], 'a')
        writefile.write(f"Generations: {str(generations)}\n")
        writefile.write(f"Iterations: {str(iterations)}\n")
        for country in list_of_countries_with_costs:
            print(country[0], country[1])
            print(country[2])
            print()
            writefile.write(f"Cost: {str(country[1])}\n")
            writefile.write(f"Cost list: {country[2]}\n")
            graph_string = "".join(country[0])
            writefile.write(f"Graph: {graph_string}\n")

    if sys.argv[1] == "genetic":
        from genetic import genetic
        generation = genetic(full_transmitter_list[:5], countrylist, 200, 5000,
                             10)
        print()
        for i in generation[:3]:
            print(i)
            print(cost(i, full_transmitter_list, transmitter_cost_list[0]))
        print()

        for list_position in range(0, len(generation)):
            wrong_neighbors = 0
            for country in range(len(generation[list_position])):
                for neighbor in countrylist[country]:
                    country = generation[list_position][country]
                    neighbor = generation[list_position][neighbor]
                    if country == neighbor:
                        wrong_neighbors += 1
            print(f"Wrong neighbors of position \