Esempio n. 1
0
def Genetic_Algorithm():

    # #files for debugging
    # f = open("responses.txt", "a")
    # f2 = open("gendata.txt", "a")

    # f2.write(str(datetime.datetime.now))
    # f.write(str(datetime.datetime.now))
    # f.close()
    # f2.close()
    agents = init_agents(population, ar)
    # for agent in agents:
    #     print(agent.ar)

    for generation in range(generations):

        print('Generation: ' + str(generation))

        agents = fitness(agents)
        # for agent in agents:
        #     print(agent.fitness)
        agents = selection(agents)
        agents = crossover(agents)
        agents = mutation(agents)
        # agents = mutation(agents)
        # agents = mutation(agents)
        print(submit(kee, agents[0].ar))
Esempio n. 2
0
import random
import statistics
import geneticFunctions

populationSize = 10
f = open("overfit.txt", "r+")
num = f.read()
num = num.replace("[", " ")
num = num.replace("]", " ")
num = num.strip()
num = num.split(", ")
for i in range(0, len(num)):
    num[i] = float(num[i])
private_key = "JVlzF9h4oeN3fyaOoSYgA1HiW82SlS1iptEqtB4lDQAeCK2k8C"
ret_val = client_moodle.get_errors(private_key, num)
ret_val2 = client_moodle.submit(private_key, num)
print(ret_val, ret_val2)
population = []
for i in range(0, populationSize):
    temp = []
    for i in range(0, 11):
        temp.append(random.uniform(-10, 10))
    population.append(temp)
nextGenPopulation = []
print("Generation: 0", end=" ")

for i in range(1, 10):
    # for i in range(0, populationSize):
    #     print(type(population[i]))
    fittestIndividualsForDirect, fittestIndividualsForCrossing, sortedFitnessValArray = geneticFunctions.naturalSelection(
        population, populationSize, private_key)
Esempio n. 3
0
    for i in range(child_number):

        print("\nChild: {}".format(i))
        child = crossover(select_mates(chromosome_probability, chromosomes))
        print("Child: {}".format(child))
        if random.randint(0, 1):
            mutate_child = child
        else:
            mutate_child = mutate(child)

        err = client_moodle.get_errors(
            '32EZBpTMqjBF5XByc7riOKvbIw2EykjhBEUqjDSAA9geHjqTaW',
            list(mutate_child))
        submit_status = client_moodle.submit(
            '32EZBpTMqjBF5XByc7riOKvbIw2EykjhBEUqjDSAA9geHjqTaW',
            list(mutate_child))

        mean_error = find_mean_error(err[0], err[1])
        min_training_error = min(min_training_error, err[0])
        min_validation_error = min(min_validation_error, err[1])
        min_error = min(min_error, mean_error)

        child_errors.append([mean_error, err[0], err[1], child])

    random_values = numpy.array(random.sample(range(population_size), 5))

    for index in random_values:
        child_errors.append(parent_error[index])
    child_errors.sort()
Esempio n. 4
0
    # new_population[parents.shape[0]:, :] = offspring_mutation

    new_population = ga.create_new_pop(parents, offspring_mutation,
                                       num_parents_to_take,
                                       num_children_to_take)

    # The best result in the current iteration.
    # print("Best result : ", numpy.max(numpy.sum(new_population*equation_inputs, axis=1)))

# Getting the best solution after iterating finishing all generations.
#At first, the fitness is calculated for each solution in the final generation.
print("final:", new_population.tolist())

print("final fitness:", fitness)
# print(fitness)
# Then return the index of that solution corresponding to the best fitness.
best_match_idx = numpy.where(fitness == numpy.min(fitness))
print("best match!", best_match_idx)
# print("Best_match_index:", best_match_idx)
ans = list(new_population[best_match_idx, :][0][0])
# ans = list(new_population[best_match_idx])
print("Best solution : ", ans)
# print("Best solution fitness : ", list(fitness[best_match_idx]))

p = list(
    client_moodle.get_errors(
        'bTcDQRvCITniLCqT38zzd4CaYs8gPsrnjxyZyIVTiTv6DyX0kX',
        list(new_population[best_match_idx, :][0][0])))
print("Best solution fitness : ", p)
client_moodle.submit('bTcDQRvCITniLCqT38zzd4CaYs8gPsrnjxyZyIVTiTv6DyX0kX', ans)
Esempio n. 5
0
def main():

    print("PC: ", pc, " POP_SIZE: ", pop_size, " ITER : ", iter)

    vector_og = [
        0.0, 0.1240317450077846, -6.211941063144333, 0.04933903144709126,
        0.03810848157715883, 8.132366097133624e-05, -6.018769160916912e-05,
        -1.251585565299179e-07, 3.484096383229681e-08, 4.1614924993407104e-11,
        -6.732420176902565e-12
    ]
    # vector_og=[-9.78736351e+00 ,-6.30079234e+00 ,-5.86904268e+00 , 4.93390314e-02,3.81084816e-02 , 8.13236610e-05, -6.01876916e-05, -1.25158557e-07,3.48409638e-08,  4.16149250e-11, -6.73242018e-12]
    to_send = [-20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20]
    min_error = -1
    min_error1 = -1
    min_error2 = -1

    parenterrors = np.zeros(pop_size)
    parenterrors1 = np.zeros(pop_size)
    parenterrors2 = np.zeros(pop_size)
    parentprobalities = np.zeros(pop_size)
    population = np.zeros((pop_size, MAX_DEG))

    # generate the population
    for i in range(pop_size):
        temp = np.copy(vector_og)
        population[i] = mutateall(temp)

    #generate errors for each individual in the population
    for j in range(pop_size):
        temp = population[j].tolist(
        )  #passing a list to the get_errors function
        err = server.get_errors(key, temp)

        #adding the two errors and storing in parenterror
        parenterrors[j] = (err[0] + err[1])
        parenterrors1[j] = (err[0])
        parenterrors2[j] = (err[1])

    bank = np.copy(population)
    bankerrors = np.copy(parenterrors)
    bankerrors1 = np.copy(parenterrors1)
    bankerrors2 = np.copy(parenterrors2)

    # have to change this to a while loop with appropriate condition later
    for iter_num in range(iter):
        new_iter = 0

        print("\n\n\n\n********" + str(iter_num) + "*********")

        # Sort the errors in ascending order
        # Least error => max fittness
        # Correspondingly sort the population also
        parenterrorsinds = parenterrors.argsort()
        parenterrors = parenterrors[parenterrorsinds[::1]]
        parenterrors1 = parenterrors1[parenterrorsinds[::1]]
        parenterrors2 = parenterrors2[parenterrorsinds[::1]]
        population = population[parenterrorsinds[::1]]

        #debug statements
        for j in range(pop_size):
            print("person " + str(j) + " error " + str(parenterrors[j]))
            print("\tvalues" + str(population[j]) + "\n\n")

        # Assign probabilities to the population
        parentprobalities = gen_parent_probabilities(pop_size)

        # Checking sum(prob) = 1
        # print(np.sum(parentprobalities))
        child_population = np.zeros((pop_size, MAX_DEG))

        #perform crossover cross_n times
        for j in range(cross_n):
            arr = crossover_select(parentprobalities)

            # Two parents chosen based on probabilities => arr[0], arr[1]
            # Sending parents for crossover
            temp = crossover(population[arr[0]], population[arr[1]])

            child_population[new_iter] = temp[0]
            new_iter += 1

            child_population[new_iter] = temp[1]
            new_iter += 1

        # print("BEFORE MUTATION: CHILD POPULATION")
        # for j in range(len(child_population)):
        #     print("Child", j)
        #     print(child_population[i])

        # Send the new population for mutation
        for j in range(pop_size):
            temp = np.copy(child_population[j])
            child_population[j] = mutation(temp)

        # print("AFTER MUTATION: CHILD POPULATION")
        # for j in range(len(child_population)):
        #     print("Child", j)
        #     print(child_population[i])

        # get the errors for the new population
        childerrors = np.zeros(pop_size)
        childerrors1 = np.zeros(pop_size)
        childerrors2 = np.zeros(pop_size)

        # generate errors for each child
        for j in range(pop_size):
            temp = child_population[j].tolist(
            )  #passing a list to the get_errors function
            err = server.get_errors(key, temp)

            #adding the two errors and storing in parnterror
            childerrors[j] = (err[0] + err[1])
            childerrors1[j] = (err[0])
            childerrors2[j] = (err[1])

        #combining parents and children into one array
        candidates = np.concatenate([population, child_population])
        candidate_errors = np.concatenate([parenterrors, childerrors])
        candidate_errors1 = np.concatenate([parenterrors1, childerrors1])
        candidate_errors2 = np.concatenate([parenterrors2, childerrors2])

        # sorting all the candidates by error
        candidateerrorsinds = candidate_errors.argsort()
        candidate_errors = candidate_errors[candidateerrorsinds[::1]]
        candidate_errors1 = candidate_errors1[candidateerrorsinds[::1]]
        candidate_errors2 = candidate_errors2[candidateerrorsinds[::1]]
        candidates = candidates[candidateerrorsinds[::1]]

        # setting the probability and choosing the indices
        # candidate_prob=gen_parent_probabilities(pop_size*2)
        # chosenindices=np.random.choice(np.arange(0,2*pop_size),pop_size, replace=False,p=candidate_prob)

        # set population for the next iteration
        ind = 0

        for i in range(2 * pop_size):
            # ind=chosenindices[i]
            if ind >= pop_size:
                break

            checkflag = 0

            for j in range(ind):
                # print(i,j,ind)
                # print(population[i],population[j])
                if check_match(candidates[i], population[j]) == 1:
                    checkflag = 1
                    break

            if (checkflag == 0):
                population[ind] = candidates[i]
                parenterrors[ind] = candidate_errors[i]
                parenterrors1[ind] = candidate_errors1[i]
                parenterrors2[ind] = candidate_errors2[i]
                ind += 1

        if (ind < pop_size):
            print("choosing from the bank from index " + str(ind))
            i = 0
            while (ind < pop_size):
                population[ind] = bank[i]
                parenterrors[ind] = bankerrors[i]
                parenterrors1[ind] = bankerrors1[i]
                parenterrors2[ind] = bankerrors2[i]
                ind += 1
                i += 1

        # set the send array by choosing the minimum from all the candidates NOTE: it may not be selected in the new population
        if (min_error == -1 or min_error > candidate_errors[0]):
            to_send = candidates[0]
            min_error = candidate_errors[0]
            min_error1 = candidate_errors1[0]
            min_error2 = candidate_errors2[0]
        print(
            "-------------------------------------------------------------------------------\n"
        )
        print("Min error = ", min_error, "\n\n")
        print("Min error1 = ", min_error1, "\n\n")
        print("Min error2 = ", min_error2, "\n\n")

        if (min_error < 40000000):
            print(
                "sending\n\n" + str(to_send) +
                "\n\nwas it successfully submitted?",
                server.submit(key, to_send.tolist()))

    return to_send
Esempio n. 6
0
                i += 1

        # set the send array by choosing the minimum from all the candidates NOTE: it may not be selected in the new population
        if (min_error == -1 or min_error > candidate_errors[0]):
            to_send = candidates[0]
            min_error = candidate_errors[0]
            min_error1 = candidate_errors1[0]
            min_error2 = candidate_errors2[0]
        print(
            "-------------------------------------------------------------------------------\n"
        )
        print("Min error = ", min_error, "\n\n")
        print("Min error1 = ", min_error1, "\n\n")
        print("Min error2 = ", min_error2, "\n\n")

        if (min_error < 40000000):
            print(
                "sending\n\n" + str(to_send) +
                "\n\nwas it successfully submitted?",
                server.submit(key, to_send.tolist()))

    return to_send


to_send = main()
print("sending\n\n" + str(to_send) + "\n\nwas it successfully submitted?",
      server.submit(key, to_send.tolist()))
print("Code finished")
print(
    "-------------------------------------------------------------------------------\n\n"
)
Esempio n. 7
0
    offspring_mutation = mutation(offspring_crossover)

    new_population[0:parents.shape[0], :] = parents
    new_population[parents.shape[0]:, :] = offspring_mutation

    print("Fitness so far : ")
    print(fitness)

fitness = cal_pop_fitness(new_population)
best_match_idx = np.where(fitness == np.min(fitness))[0][0]

print('all weights')
print(new_population)

weights_vector = new_population[best_match_idx, :]

print("weights_vector")
print(weights_vector)
print("Best solution fitness : ", fitness[best_match_idx])

print("errors:")
error(get_errors(team_secret_key, list(weights_vector)))
new_error = cal_pop_fitness([weights_vector])
submit(team_secret_key, list(weights_vector))

# submit stuff
if new_error < prev_error:
    print('BETTER :):):):):)')
    file = open("lulli.txt", 'w+')
    file.write(str(list(weights_vector)))
Esempio n. 8
0
def main():
    w1=0.2
    w2=0.8
    print("PC: " ,pc, " POP_SIZE: ",pop_size," ITER : ", iter, "w1: ",w1,"w2: ",w2, "Stop : ", "50")

    vector_og=[0.0, 0.1240317450077846, -6.211941063144333, 0.04933903144709126, 0.03810848157715883, 8.132366097133624e-05, -6.018769160916912e-05, -1.251585565299179e-07, 3.484096383229681e-08, 4.1614924993407104e-11, -6.732420176902565e-12]
    # vector_og=[-9.78736351e+00 ,-6.30079234e+00 ,-5.86904268e+00 , 4.93390314e-02,3.81084816e-02 , 8.13236610e-05, -6.01876916e-05, -1.25158557e-07,3.48409638e-08,  4.16149250e-11, -6.73242018e-12]
    to_send=[-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20]
    min_error=-1
    min_error1=-1
    min_error2=-1

    parenterrors=np.zeros(pop_size)
    parenterrors1=np.zeros(pop_size)
    parenterrors2=np.zeros(pop_size)
    parentprobalities=np.zeros(pop_size)
    population=np.zeros((pop_size,MAX_DEG))

    # generate the population 
    for i in range(pop_size):
        temp=np.copy(vector_og)
        population[i]=mutateall(temp)

    #generate errors for each individual in the population
    for j in range(pop_size):
        temp=population[j].tolist() #passing a list to the get_errors function
        err=server.get_errors(key,temp)
        
        #adding the two errors and storing in parenterror
        parenterrors[j]=(w1*err[0]+w2*err[1])
        parenterrors1[j]=(err[0])
        parenterrors2[j]=(err[1])

    # have to change this to a while loop with appropriate condition later
    for iter_num in range(iter):
        new_iter=0
        if(iter_num > 50 ):
            w1=1
            w2=1

        print("\n\n\n\n********"+str(iter_num)+"*********")


        # Sort the errors in ascending order
        # Least error => max fittness
        # Correspondingly sort the population also
        # arrinds=sortfunc(parenterrors,parenterrors1,parenterrors2)
        parenerrorsinds=parenterrors.argsort()
        parenterrors=parenterrors[parenerrorsinds[::1]]
        parenterrors1=parenterrors1[parenerrorsinds[::1]]
        parenterrors2=parenterrors2[parenerrorsinds[::1]]
        population=population[parenerrorsinds[::1]]

        #debug statements
        for j in range(pop_size):
            print("person " + str(j)+" error "+ str(parenterrors[j]))
            print("\tvalues"+str(population[j])+"\n\n")

        # Assign probabilities to the population
        parentprobalities=gen_parent_probabilities(pop_size)
        
        # Checking sum(prob) = 1
        # print(np.sum(parentprobalities))
        child_population=np.zeros((pop_size,MAX_DEG))

        #perform crossover cross_n times
        for j in range (cross_n):
            arr=crossover_select(parentprobalities)
            
            # Two parents chosen based on probabilities => arr[0], arr[1]
            # Sending parents for crossover
            temp=crossover(population[arr[0]],population[arr[1]])
            
            child_population[new_iter]=temp[0]
            new_iter+=1

            child_population[new_iter]=temp[1]    
            new_iter+=1

        # Send the new population for mutation
        for j in range(pop_size):
            temp=np.copy(child_population[j])
            child_population[j]=mutation(temp)

        # get the errors for the new population
        childerrors=np.zeros(pop_size)
        childerrors1=np.zeros(pop_size)
        childerrors2=np.zeros(pop_size)

        # generate errors for each child
        for j in range(pop_size):
            temp=child_population[j].tolist() #passing a list to the get_errors function
            err=server.get_errors(key,temp)
            
            #adding the two errors and storing in parenterror
            childerrors[j]=(w1*err[0]+w2*err[1])
            childerrors1[j]=(err[0])
            childerrors2[j]=(err[1])

        #combining parents and children into one array
        candidates=np.concatenate([population,child_population])
        candidate_errors=np.concatenate([parenterrors,childerrors])
        candidate_errors1=np.concatenate([parenterrors1,childerrors1])
        candidate_errors2=np.concatenate([parenterrors2,childerrors2])

        # sorting all the candidates by error
        # arrinds=sortfunc(candidate_errors,candidate_errors1, candidate_errors2)
        candidate_errors_inds=candidate_errors.argsort()
        candidate_errors=candidate_errors[candidate_errors_inds[::1]]
        candidate_errors1=candidate_errors1[candidate_errors_inds[::1]]
        candidate_errors2=candidate_errors2[candidate_errors_inds[::1]]
        candidates=candidates[candidate_errors_inds[::1]]

        # set population for the next iteration by selecting the best k in the candidaes
        for i in range(pop_size):
            population[i]=candidates[i]
            parenterrors[i]=candidate_errors[i]
            parenterrors1[i]=candidate_errors1[i]
            parenterrors2[i]=candidate_errors2[i]

        # set the send array by choosing the minimum from all the candidates NOTE: it may not be selected in the new population 
        if(min_error==-1 or min_error>candidate_errors[0]):
            to_send=candidates[0]
            min_error=candidate_errors[0]
            min_error1=candidate_errors1[0]
            min_error2=candidate_errors2[0]
        print("-------------------------------------------------------------------------------\n")
        print("Min error = ", min_error,"\n\n")
        print("Min error1 = ", min_error1,"\n\n")
        print("Min error2 = ", min_error2,"\n\n")

        if(min_error<40000000):
            print("sending\n\n"+str(to_send)+"\n\nwas it successfully submitted?", server.submit(key,to_send.tolist()))
            
    return to_send
Esempio n. 9
0
        candidate_errors1=candidate_errors1[candidate_errors_inds[::1]]
        candidate_errors2=candidate_errors2[candidate_errors_inds[::1]]
        candidates=candidates[candidate_errors_inds[::1]]

        # set population for the next iteration by selecting the best k in the candidaes
        for i in range(pop_size):
            population[i]=candidates[i]
            parenterrors[i]=candidate_errors[i]
            parenterrors1[i]=candidate_errors1[i]
            parenterrors2[i]=candidate_errors2[i]

        # set the send array by choosing the minimum from all the candidates NOTE: it may not be selected in the new population 
        if(min_error==-1 or min_error>candidate_errors[0]):
            to_send=candidates[0]
            min_error=candidate_errors[0]
            min_error1=candidate_errors1[0]
            min_error2=candidate_errors2[0]
        print("-------------------------------------------------------------------------------\n")
        print("Min error = ", min_error,"\n\n")
        print("Min error1 = ", min_error1,"\n\n")
        print("Min error2 = ", min_error2,"\n\n")

        if(min_error<40000000):
            print("sending\n\n"+str(to_send)+"\n\nwas it successfully submitted?", server.submit(key,to_send.tolist()))
            
    return to_send

to_send=main()
print("sending\n\n"+str(to_send)+"\n\nwas it successfully submitted?", server.submit(key,to_send.tolist()))
print("Code finished")
print("-------------------------------------------------------------------------------\n\n")
Esempio n. 10
0
# import tester as server
import client_moodle as server
key = '847FWwSwTAxKTPvfixjzNnxbeudiTzJ9psoVIdUxqehtQ5efNo'

lst=[]
# creating an empty list
lst1 =input().split()
lst2 =input().split()
lst3 =input().split()
for i in range(0,4):
    lst.append(float(lst1[i]))
    
for i in range(0,4):
    lst.append(float(lst2[i]))
    
for i in range(0,3):
    lst.append(float(lst3[i]))
    

print(lst)
print("sending\n\n"+str(lst)+"\n\nwas it successfully submitted?", server.submit(key,lst))
print("Code finished")
print("-------------------------------------------------------------------------------\n\n")
Esempio n. 11
0
# import tester as server
import client_moodle as server
key = '847FWwSwTAxKTPvfixjzNnxbeudiTzJ9psoVIdUxqehtQ5efNo'

# creating an empty list
lst = input().split()
print(lst)
for i in range(0, 11):
    lst[i] = float(lst[i])
print("sending\n\n" + str(lst) + "\n\nwas it successfully submitted?",
      server.submit(key, lst))
print("Code finished")
print(
    "-------------------------------------------------------------------------------\n\n"
)
Esempio n. 12
0
import client_moodle as cli, pickle

fname = 'topvec.pkl'
f = open(fname, 'rb')
vector = pickle.load(f)
res1 = cli.get_errors('jcikTU98ZdeaUH5uBHsOPXzXAzAhBVdwtDDj7SqoF98mqbjZLw',
                      vector)
print(res1)
res2 = cli.submit('jcikTU98ZdeaUH5uBHsOPXzXAzAhBVdwtDDj7SqoF98mqbjZLw', vector)
print(res2)