コード例 #1
0
ファイル: mga1.py プロジェクト: bits-plz/ga_
def m_ga1(func,nvar,varmin,varmax,maxit,npop,optimization,thread_it,selection_type,x_type,gamma=0.1,mu=0.1,sigma=0.1,beta=1,pc=1):
    if(len(res)>0):
        res.clear()
    in_it=datetime.now()
    global q
    problem = structure()
    #here in the elifs you can add the make the func what you added above
    if "x^" in func:
        p,q=func.split("^")
        problem.costfunc=sphere
    elif func=='@rastrigin':#it's your choice what you add here like i enter func name as @rastrigin and the function called is rastrigin
        problem.costfunc=rastrigin
    elif func =="@ackley":
        problem.costfunc=ackley_path
    elif func=="@schwefel":
        problem.costfunc=schwefel
    elif func=="@griewangk":
        problem.costfunc=griewangk
    else:
        problem.costfunc=func_eval
    problem.func_expr=func
    problem.nvar = nvar
    varmin=varmin.split(',')
    varmax=varmax.split(',')
    problem.varmin = []
    problem.varmax=[]
    for item in varmin:
        problem.varmin.append(float(item))
    for item in varmax:
        problem.varmax.append(float(item))


    params = structure()
    params.maxit = maxit#the max iterations required
    params.npop = npop#the initial population 
    params.pc = pc
    params.gamma = gamma
    params.mu = mu#mutation rate
    params.sigma = sigma
    params.beta=beta
    params.optimization=optimization
    params.selection_type=selection_type
    params.x_type=x_type
    # run ga    
    if(thread_it=="Yes"):
        t=threading.Thread(target=wrapper,args=(ga.run_ga,(problem,params),res))
        t.start()
        while(len(res)==0):
            pass
        t.join()
        print(res)
        result = res[0]
    else:
        result=ga.run_ga(problem,params)
    std=np.std([x['cost'] for x in result.pop])
    fin_time=datetime.now()
    print(f"execution time is {fin_time-in_it}")
    print(f"following are the last offsprings {result.bestsol['position']}")
    print(f"the cost is {result.bestsol['cost']}")
    return result,std,result.bestsol['position']
コード例 #2
0
def main():
    filenames = [
        "Datasets/breast-cancer-wisconsin.csv", "Datasets/glass.csv",
        "Datasets/soybean-small - Copy.csv", "Datasets/abalone.csv",
        "Datasets/machine.csv", "Datasets/forestfires.csv"
    ]

    ## IMPORT CLASSIFICATION DATA SETS: BREAST CANCER, GLASS, SOYBEAN
    brc_data = create_data_set(filenames[0], False)
    gla_data = create_data_set(filenames[1], False)
    soy_data = create_data_set(filenames[2], False)

    ## IMPORT REGRESSION DATA SETS: ABALONE, COMPUTER HARDWARE, FOREST FIRES
    aba_data = create_data_set(filenames[3], True)
    mac_data = create_data_set(filenames[4], True)
    fof_data = create_data_set(filenames[5], True)

    ## RUN GENETIC ALGORITHM
    ### run_ga(data_object, n_hidden, l_rate, n_epoch, size, n_parents)
    run_ga(aba_data, 1, 0.1, 50, 200, 100)
コード例 #3
0
def run(args):
    rundir, maxiter = args

    if not os.path.exists(rundir):
        os.mkdir(rundir)
    os.chdir(rundir)

    sys.stdout = open('out.txt', 'a')
    sys.stderr = open('err.txt', 'w')

    try:
        if not os.path.exists('godb.db'):
            prepare_ga(splits={(2, 2): 1, (2, ): 2, (1, ): 1}, N=N)
        run_ga(maxiter, kptdensity=kptdensity)
    except:
        traceback.print_exc()
        sys.stderr.flush()
        raise

    os.chdir('..')
    return
コード例 #4
0
def run(args):
    ''' This method specifies how to conduct a global optimization
    search, accepting a (run_directory, maximum_iterations)
    tuple as required by TANGO.
    '''
    rundir, maxiter = args

    # Create the run directory if it doesn't already exist:
    if not os.path.exists(rundir):
        os.mkdir(rundir)
    os.chdir(rundir)

    # Redirect the standard output and error to local files:
    sys.stdout = open('out.txt', 'a')
    sys.stderr = open('err.txt', 'w')

    try:
        # Create a database with N initial random structures
        # (N is here a global variable set in the __main__
        # function):
        if not os.path.exists('godb.db'):
            prepare_ga(N=N)
            #prepare_ga(splits={(2, 2): 1, (2,): 2, (1,): 1}, N=N)
        # Run the genetic algorithm (kptdensity is another
        # global variable set in the __main__ function):
        run_ga(maxiter, kptdensity=kptdensity)
    except:
        # When using the multiprocessing module
        # we need to explicitly print the error
        # traceback:
        traceback.print_exc()
        sys.stderr.flush()
        raise

    os.chdir('..')
    return
コード例 #5
0
def get_best_features(title, X, y, keys, heavy):

    print 'get_best_features(title="%s", X=%s, y=%s, keys=%s, heavy=%s)' % (title, X.shape, y.shape, 
        len(keys), heavy)

    num_features = X.shape[1]

    def eval_func(chromosome):
        indexes = [chromosome[i] for i in range(len(chromosome))]
        Xf = X[:,indexes]
        score = get_cv_score(Xf, y)
        #print '  eval %.4f %3d %s' % (score, len(indexes), indexes)
        return score

    allowed_values = range(num_features)
    all_results = {}
    best_genomes = None
    #for n in range(1, num_features+1):
    for n in range(1, 14):
    #for n in range(1, 3):
        genome_len = n
        if heavy:
            results = GAX.run_ga2(eval_func, genome_len, allowed_values, 5, best_genomes)
        else:    
            results = GAX.run_ga(eval_func, genome_len, allowed_values, best_genomes)
        
        # results are sorted best to worst so this gets best results
        all_results[n] = results[0] 
        last_score = 0.0
        for k in sorted(all_results.keys()):
            score = all_results[k]['score']
            genome = all_results[k]['genome']
            decoded = [keys[g] for g in genome]
            print '%6d: %.3f (%.4f) %s %s' % (k, score, score-last_score, genome, decoded)
            last_score = score
        best_genomes = [r['genome'] for r in results]    
    return all_results    
コード例 #6
0
def single_run(toolkit, run_dir, verbose=True):
    """Perform a single run of the genetic algorithm.

    Parameters:
    - toolkit: Toolkit object containing the operators and the fitness
               function, to be passed to the GA procedure.
    - run_dir: directory to which the log data should be saved for
               the run
    - verbose: if False, nothing is printed to stdout.

    Returns the best individual and its fitness, the entire population
    after all generations and the execution stats."""
    config = toolkit.config

    if not os.path.exists(run_dir):
        os.makedirs(run_dir)

    start_time = time.time()

    pop = toolkit.init_pop()
    fit_and_pop, stats = run_ga(pop, config['GA']['Gens'], toolkit, verbose)

    best_fitness, best = min(fit_and_pop)

    end_time = time.time()
    duration = end_time - start_time  # in seconds

    best_final_cube = rc.apply_moves(toolkit.initial_cube, best)
    if verbose:
        pprint.pprint(best, indent=4, compact=True)
        print("Fitness:", best_fitness)
        rc.print_3d_cube(best_final_cube)

    log_run(run_dir, config, stats, duration)
    log_individuals(run_dir, fit_and_pop, best_final_cube)

    return (best_fitness, best), pop, stats
コード例 #7
0
ファイル: main.py プロジェクト: f-matt/pybrain-examples
#!/usr/bin/python

from ann import create_ann
from ga import run_ga

if __name__ == "__main__":
    # create_ann()
    run_ga()
    print "ok"



コード例 #8
0
def main(args):
    fs, freq, fourier = get_fft(args[1])
    print(run_ga(fourier))
コード例 #9
0
ファイル: RunTraining.py プロジェクト: olinoskar/simulations
    args = parser.parse_args()

    if not args.path or not args.network_layout:
        print('Path and network layout must be passed as arguments. Exiting!')
        import sys
        sys.exit()

    path = args.path
    stoch = args.stochastic_spawning
    layout_str = args.network_layout
    generations = args.generations
    pop_size = args.pop_size

    layout = []
    for s in layout_str.split(','):
        layout.append(int(s))

    print('Saving to: ', path)
    print('Stochastic spawning:', stoch)
    print('Network layout:', layout)
    print('==============================')

    run_ga(
        path=path,
        network_shape=layout,
        fitness_function='score',
        stochastic_spawning=stoch,
        generations=generations,
        population_size=pop_size,
    )
コード例 #10
0
ファイル: run_ga.py プロジェクト: bnhalder/basic_ml
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 19 20:32:00 2017

@author: jabong
"""

import ga
import pylab as pl
import fourpeaks as fF

pl.ion()
pl.show()

plotfig = pl.figure()

ga = ga.ga(30, 'fF.fourpeaks', 301, 500, -1, 'un', 4, False)
ga.run_ga(plotfig)

pl.pause(0)