Exemplo n.º 1
0
def RHC():
    correctCount = 0
    RHC_iters = 10
    t=0
    totalTime =0
    totalIters = 0

    global rhc
    rhc = RandomizedHillClimbing(hcp)
    while correctCount < NUM_RIGHT:
        # print str(correctCount)+  " / 20 correct in RHC w/ iters " + str(RHC_iters)
        fit = FixedIterationTrainer(rhc, RHC_iters)
        start = time.time()
        fitness = fit.train()
        t = time.time() - start
        totalIters+=RHC_iters
        totalTime += t;
        myWriter.addValue(fitness, "RHC_fitness", runNum)
        myWriter.addValue(t, "RHC_searchTimes",runNum)
        v = ef.value(rhc.getOptimal())
        if v == N:
            correctCount += 1
        else:
            correctCount = 0
            #RHC_iters += 1
    myWriter.addValue(totalTime,"RHC_times",runNum)
    myWriter.addValue(totalIters,"RHC_iters",runNum)
    print str(N) + ": RHC: " + str(ef.value(rhc.getOptimal()))+" took "+str(totalTime)+" seconds and " + str(totalIters) + " iterations"
Exemplo n.º 2
0
def SA():
    SA_iters = 10
    correctCount = 0
    t=0
    totalTime=0
    totalIters =0
    global sa
    sa = SimulatedAnnealing(1e11, .85, hcp)
    while correctCount < NUM_RIGHT:
        start = time.time()
        fit = FixedIterationTrainer(sa, SA_iters)
        fitness = fit.train()
        t = time.time() - start
        totalTime+=t
        totalIters+= SA_iters
        myWriter.addValue(fitness, "SA_fitness", runNum)
        myWriter.addValue(t, "SA_searchTimes",runNum)
        v = ef.value(sa.getOptimal())
        if v == N:
            correctCount += 1
        else:
            correctCount = 0
            #SA_iters += 1
    myWriter.addValue(t,"SA_times",0)
    myWriter.addValue(int(SA_iters),"SA_iters",0)
    print str(N) + ": SA: " + str(ef.value(sa.getOptimal())) + " took "+str(totalIters)+ " seconds and " + str(totalIters) + " iterations"
Exemplo n.º 3
0
def MIMICtest():
    correctCount = 0
    MIMIC_iters = 10
    MIMIC_samples = 5*N #max(1,int(N/10))
    MIMIC_keep = int(.1 * MIMIC_samples)
    t=0
    while correctCount < NUM_RIGHT and MIMIC_iters <= 500:
        MIMIC_keep = int( max(.1 * MIMIC_samples, 1))
        mimic = MIMIC(int(MIMIC_samples), int(MIMIC_keep), pop)
        start = time.time()
        fit = FixedIterationTrainer(mimic, int(MIMIC_iters))
        fitness = fit.train()
        t = time.time() - start
        v = ef.value(mimic.getOptimal())
        myWriter.addValue(fitness, "MIMIC_fitness", runNum)
        myWriter.addValue(t, "MIMIC_searchTimes",runNum)
        if v==N:
            correctCount +=1
        else:
            correctCount = 0
            MIMIC_iters *=1.1
            MIMIC_samples *=1.1
    myWriter.addValue(t,"MIMIC_times",0)
    myWriter.addValue(int(MIMIC_iters),"MIMIC_iters",0)
    myWriter.addValue(int(MIMIC_samples),"MIMIC_samples",0)
    myWriter.addValue(int(MIMIC_keep),"MIMIC_keep",0)


    print(str(N) + ": MIMIC: " + str(ef.value(mimic.getOptimal())) + " took " + str(t) +
    " seconds and " + str(int(MIMIC_iters)) + " iterations and " + str(int(MIMIC_samples)) +
    " samples with keep " + str(int(MIMIC_keep)))
Exemplo n.º 4
0
def mimicGATest():

    popBegin   = 1
    popEnd     = 101
    keepBegin  = 1
    keepEnd    = 90
    mutBegin   = 1
    mutEnd     = 90
    itersBegin = 1
    itersEnd   = 200

    samples = 10
    keep = 2

    problemSize = N
    mimicRange = (problemSize)
    iters = 1

    paramRanges = Vector(8)
    paramRanges.addElement(popBegin)
    paramRanges.addElement(popEnd)
    paramRanges.addElement(keepBegin)
    paramRanges.addElement(keepEnd)
    paramRanges.addElement(mutBegin)
    paramRanges.addElement(mutEnd)
    paramRanges.addElement(itersBegin)
    paramRanges.addElement(itersEnd)

    totalParamSize1 = (popEnd - popBegin +1) + (keepEnd - keepBegin +1) + (mutEnd - mutBegin +1) + (itersEnd - itersBegin +1)
    allParamValues = range(popBegin, popEnd+1)+range(keepBegin, keepEnd+1)+range(mutBegin, mutEnd+1)+range(itersBegin, itersEnd+1)
    totalParamSize = len(allParamValues)
    metaFun = RamysEvalMetafunc(ranges)
    discreteDist = RamysMimicDistribution(paramRanges) #DiscreteUniformDistribution(problemSize)
    distFunc = DiscreteDependencyTree(.1, allParamValues)
    findGA = GenericProbabilisticOptimizationProblem(metaFun, discreteDist, distFunc)
    mimic = MIMIC(samples, keep, findGA)
    fit = FixedIterationTrainer(mimic, iters)
    fit.train()
    print str(N) + ": MIMIC finds GA : " + str(ef.value(mimic.getOptimal()))
Exemplo n.º 5
0
def main():

    iterations = 200000
    alg = 'all'
    gaPop = 2000
    gaMate = 1500
    gaMutate = 250
    mimicSamples = 500
    mimicToKeep = 100
    saTemp = 1E12
    saCooling = .999
    gaIters = 1000
    mimicIters = 1000
    run = 0
    settings = []

    try:
        opts, args = getopt.getopt(sys.argv[1:], "ahrsgmn:i:", ["gaIters=", "mimicIters=", "gaPop=", "gaMate=", "gaMutate=", "mimicSamples=", "mimicToKeep=", "saTemp=", "saCooling="])
    except:
        print 'travelingsalesman.py -i <iterations>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'travelingsalesman.py -i <iterations>'
            sys.exit(1)
        elif opt == '-i':
            if arg < 1:
                print 'Iterations must be greater than 0'
                sys.exit(2)
            iterations = int(arg)
        elif opt == '-a':
            alg = 'all'
        elif opt == '-r':
            alg = 'RHC'
        elif opt == '-s':
            alg = 'SA'
        elif opt == '-g':
            alg = 'GA'
        elif opt == '-m':
            alg = 'MIMIC'
        elif opt == '--gaPop':
            if arg < 1:
                print 'Population must be greater than 0'
                sys.exit(2)
            gaPop = int(arg)
        elif opt == '--gaMate':
            if arg < 1:
                print 'Mating must be greater than 0'
                sys.exit(2)
            gaMate = int(arg)
        elif opt == '--gaMutate':
            if arg < 1:
                print 'Mutators must be greater than 0'
                sys.exit(2)
            gaMutate = int(arg)
        elif opt == '--mimicSamples':
            if arg < 1:
                print 'MIMIC samples must be greater than 0'
                sys.exit(2)
            mimicSamples = int(arg)
        elif opt == '--mimicToKeep':
            if arg < 1:
                print 'MIMIC to keep must be greater than 0'
                sys.exit(2)
            mimicToKeep = int(arg)
        elif opt == '--saTemp':
            saTemp = float(arg)
        elif opt == '--saCooling':
            saCooling = float(arg)
        elif opt == '-n':
            run = int(arg)
        elif opt == '--gaIters':
            if arg < 1:
                print 'GA Iterations must be greater than 0'
                sys.exit(2)
            gaIters = int(arg)
        elif opt == '--mimicIters':
            if arg < 1:
                print 'MIMIC Iterations must be greater than 0'
                sys.exit(2)
            mimicIters = int(arg)

    vars = {
            'iterations' : iterations,
            'alg' : alg,
            'gaPop' : gaPop,
            'gaMate' : gaMate,
            'gaMutate' : gaMutate,
            'mimicSamples' : mimicSamples,
            'mimicToKeep' : mimicToKeep,
            'saTemp' : saTemp,
            'saCooling' : saCooling,
            'gaIters' : gaIters,
            'mimicIters' : mimicIters,
            'run' : run
            }

    settings = getSettings(alg, settings, vars)
    if gaPop < gaMate or gaPop < gaMutate or gaMate < gaMutate:
        pebkac({gaPop: 'total population',gaMate : 'mating population', gaMutate : 'mutating population'}, alg, 'total population', settings)
    if mimicSamples < mimicToKeep:
        pebkac({mimicSamples: 'mimic samples', mimicToKeep : 'mimic to keep'}, alg, 'mimic samples', settings)
    prob = 'Traveling Sales Problem'
    invDist = {}
    cities = CityList()
    N = len(cities)
    #random = Random()
    points = [[0 for x in xrange(2)] for x in xrange(N)]
    for i in range(0, len(points)):
        coords = cities.getCoords(i)
        points[i][0] = coords[0]
        points[i][1] = coords[1]
    ef = TravelingSalesmanRouteEvaluationFunction(points)
    odd = DiscretePermutationDistribution(N)
    nf = SwapNeighbor()
    mf = SwapMutation()
    cf = TravelingSalesmanCrossOver(ef)
    hcp = GenericHillClimbingProblem(ef, odd, nf)
    gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
    rows = []


    if alg == 'RHC' or alg == 'all':
        print '\n----------------------------------'
        print 'Using Random Hill Climbing'
        for label, setting in settings:
            print label + ":" + str(setting)
        rhc = RandomizedHillClimbing(hcp)
        fit = FixedIterationTrainer(rhc, iterations)
        fit.train()
        path = []
        for x in range(0,N):
            path.append(rhc.getOptimal().getDiscrete(x))
        output(prob, 'RHC', path, points, settings)
        rows = []
        row = []
        row.append("Inverse of Distance")
        row.append(ef.value(rhc.getOptimal()))
        rows.append(row)
        invDist['RHC'] = ef.value(rhc.getOptimal())
        buildFooter(prob, 'RHC', rows, settings)
        outputFooter(prob, 'RHC', rows, settings)


    if alg == 'SA' or alg == 'all':
        print 'Using Simulated Annealing'
        for label, setting in settings:
            print label + ":" + str(setting)
        sa = SimulatedAnnealing(saTemp, saCooling, hcp)
        fit = FixedIterationTrainer(sa, iterations)
        fit.train()
        path = []
        for x in range(0,N):
            path.append(sa.getOptimal().getDiscrete(x))
        output(prob, 'SA', path, points, settings)
        rows = []
        row = []
        row.append("Inverse of Distance")
        row.append(ef.value(sa.getOptimal()))
        rows.append(row)
        invDist['SA'] = ef.value(sa.getOptimal())
        buildFooter(prob, 'SA', rows, settings)
        outputFooter(prob, 'SA', rows, settings)

    if alg == 'GA' or alg == 'all':
        print '\n----------------------------------'
        print 'Using Genetic Algorithm'
        for label, setting in settings:
            print label + ":" + str(setting)
        ga = StandardGeneticAlgorithm(gaPop, gaMate, gaMutate, gap)
        fit = FixedIterationTrainer(ga, gaIters)
        fit.train()
        path = []
        for x in range(0,N):
            path.append(ga.getOptimal().getDiscrete(x))
        output(prob, 'GA', path, points, settings)
        rows = []
        row = []
        row.append("Inverse of Distance")
        row.append(ef.value(ga.getOptimal()))
        rows.append(row)
        invDist['GA'] = ef.value(ga.getOptimal())
        buildFooter(prob, 'GA', rows, settings)
        outputFooter(prob, 'GA', rows, settings)

    if alg == 'MIMIC' or alg == 'all':
        print '\n----------------------------------'
        print 'Using MIMIC'
        for label, setting in settings:
            print label + ":" + str(setting)
        # for mimic we use a sort encoding
        ef = TravelingSalesmanSortEvaluationFunction(points);
        fill = [N] * N
        ranges = array('i', fill)
        odd = DiscreteUniformDistribution(ranges);
        df = DiscreteDependencyTree(.1, ranges);
        pop = GenericProbabilisticOptimizationProblem(ef, odd, df);
        mimic = MIMIC(mimicSamples, mimicToKeep, pop)
        fit = FixedIterationTrainer(mimic, mimicIters)
        fit.train()
        path = []
        optimal = mimic.getOptimal()
        fill = [0] * optimal.size()
        ddata = array('d', fill)
        for i in range(0,len(ddata)):
            ddata[i] = optimal.getContinuous(i)
        order = ABAGAILArrays.indices(optimal.size())
        ABAGAILArrays.quicksort(ddata, order)
        output(prob, 'MIMIC', order, points, settings)
        rows = []
        row = []
        row.append("Inverse of Distance")
        row.append(ef.value(mimic.getOptimal()))
        rows.append(row)
        invDist['MIMIC'] = ef.value(mimic.getOptimal())
        buildFooter(prob, 'MIMIC', rows, settings)
        outputFooter(prob, 'MIMIC', rows, settings)


    maxn = max(len(key) for key in invDist)
    maxd = max(len(str(invDist[key])) for key in invDist)
    print "Results"
    for result in invDist:
        print "%-*s %s %-*s" % (len('Best Alg') + 2, result, ':', maxd, invDist[result])
    if alg == 'all':
        print "%-*s %s %-*s" % (len('Best Alg') + 2, 'Best Alg', ':', maxd, max(invDist.iterkeys(), key=(lambda key: invDist[key])))
    print '----------------------------------'
Exemplo n.º 6
0
   runs : number of runs to average over
"""

fill = [2] * N
ranges = array('i', fill)

ef = CountOnesEvaluationFunction()
odd = DiscreteUniformDistribution(ranges)
nf = DiscreteChangeOneNeighbor(ranges)
mf = DiscreteChangeOneMutation(ranges)
cf = SingleCrossOver()
df = DiscreteDependencyTree(.1, ranges)
hcp = GenericHillClimbingProblem(ef, odd, nf)
gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

t0 = time.time()
calls = []
results = []
for _ in range(runs):
    mimic = MIMIC(samples, tokeep, pop)
    fit = FixedIterationTrainer(mimic, 100)
    fitness = fit.train()
    results.append(ef.value(mimic.getOptimal()))
    calls.append(ef.getTotalCalls())
    ef.clearCount()
print "MIMIC, average results, " + str(sum(results)/float(runs)) + ", countones_MIMIC-%d-%d-%d.txt" % (N, samples, tokeep)
print "MIMIC, average feval calls , " + str(sum(calls)/float(runs)) + ", countones_MIMIC-%d-%d-%d.txt" % (N, samples, tokeep)
t1 = time.time() - t0
print "MIMIC, average time , " + str(t1/float(runs)) + ", countones_MIMIC-%d-%d-%d.txt" % (N, samples, tokeep)
Exemplo n.º 7
0
    ef2 = TravelingSalesmanRouteEvaluationFunction(points)
    fill = [N] * N
    ranges = array('i', fill)
    odd2 = DiscreteUniformDistribution(ranges)
    df = DiscreteDependencyTree(.1, ranges)
    pop = GenericProbabilisticOptimizationProblem(ef2, odd2, df)

    rhc = RandomizedHillClimbing(hcp)
    sa = SimulatedAnnealing(SA_TEMPERATURE, SA_COOLING_FACTOR, hcp)
    ga = StandardGeneticAlgorithm(GA_POPULATION, GA_CROSSOVER, GA_MUTATION,
                                  gap)
    mimic = MIMIC(MIMIC_SAMPLES, MIMIC_TO_KEEP, pop)

    for n_iteration in iterations:
        fit_rhc = FixedIterationTrainer(rhc, n_iteration * 200)
        fit_sa = FixedIterationTrainer(sa, n_iteration * 200)
        fit_ga = FixedIterationTrainer(ga, n_iteration)
        fit_mimic = FixedIterationTrainer(mimic, n_iteration)

        print("calculating the %d th iteration" % n_iteration)

        # Training
        start_rhc = time.time()
        fit_rhc.train()
        end_rhc = time.time()

        start_sa = time.time()
        fit_sa.train()
        end_sa = time.time()
Exemplo n.º 8
0
df = DiscreteDependencyTree(.1, ranges)
hcp = GenericHillClimbingProblem(ef, odd, nf)
gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

# RHC
for t in range(numTrials):
    fname = outfile.replace('@ALG@', 'RHC').replace('@N@', str(t + 1))
    with open(fname, 'w') as f:
        f.write('iterations,fitness,time,fevals\n')
    ef = FlipFlopEvaluationFunction()
    odd = DiscreteUniformDistribution(ranges)
    nf = DiscreteChangeOneNeighbor(ranges)
    hcp = GenericHillClimbingProblem(ef, odd, nf)
    rhc = RandomizedHillClimbing(hcp)
    fit = FixedIterationTrainer(rhc, 10)
    times = [0]
    for i in range(0, maxIters, 10):
        start = clock()
        fit.train()
        elapsed = time.clock() - start
        times.append(times[-1] + elapsed)
        fevals = ef.fevals
        score = ef.value(rhc.getOptimal())
        ef.fevals -= 1
        st = '{},{},{},{}\n'.format(i, score, times[-1], fevals)
        print st
        with open(fname, 'a') as f:
            f.write(st)

# SA
ef = FourPeaksEvaluationFunction(T)
odd = DiscreteUniformDistribution(ranges)
nf = DiscreteChangeOneNeighbor(ranges)
mf = DiscreteChangeOneMutation(ranges)
cf = SingleCrossOver()
df = DiscreteDependencyTree(.1, ranges)
hcp = GenericHillClimbingProblem(ef, odd, nf)
gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

t0 = time.time()
calls = []
results = []
for _ in range(runs):
    rhc = RandomizedHillClimbing(hcp)
    fit = FixedIterationTrainer(rhc, iters)
    fitness = fit.train()
    results.append(ef.value(rhc.getOptimal()))
    calls.append(ef.getTotalCalls())
    ef.clearCount()
print "RHC, average results , " + str(sum(results) / float(runs))
print "RHC, average feval calls , " + str(sum(calls) / float(runs))
t1 = time.time() - t0
print "RHC, average time , " + str(float(t1) / runs)

t0 = time.time()
calls = []
results = []
for _ in range(runs):
    sa = SimulatedAnnealing(1E11, .95, hcp)
    fit = FixedIterationTrainer(sa, iters)
Exemplo n.º 10
0
        nf = SwapNeighbor()
        mf = SwapMutation()
        cf = TravelingSalesmanCrossOver(ef)
        hcp = GenericHillClimbingProblem(ef, odd, nf)
        gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)

        ef = TravelingSalesmanSortEvaluationFunction(points);
        fill = [N] * N
        ranges = array('i', fill)
        odd = DiscreteUniformDistribution(ranges);
        df = DiscreteDependencyTree(.1, ranges);
        pop = GenericProbabilisticOptimizationProblem(ef, odd, df);

        start = time.time()
        mimic = MIMIC(param[0], param[1], pop)
        fit = FixedIterationTrainer(mimic, num_iterations)
        fit.train()
        value = str(ef.value(mimic.getOptimal()))
        print "MIMIC Inverse of Distance: " + value
        end = time.time()
        print "Route:"
        path = []
        optimal = mimic.getOptimal()
        fill = [0] * optimal.size()
        ddata = array('d', fill)
        for i in range(0, len(ddata)):
            ddata[i] = optimal.getContinuous(i)
        order = ABAGAILArrays.indices(optimal.size())
        ABAGAILArrays.quicksort(ddata, order)
        print order
        end = time.time()
Exemplo n.º 11
0
def main():
    N=200
    tempDenom = 5
    T=N/tempDenom
    fill = [2] * N
    ranges = array('i', fill)
    iterations = 2000
    gaIters = 1000
    mimicIters = 1000
    gaPop = 200
    gaMate = 100
    gaMutate = 10
    mimicSamples = 200
    mimicToKeep = 20
    saTemp = 1E11
    saCooling = .95
    alg = 'all'
    run = 0
    settings = []

    try:
       opts, args = getopt.getopt(sys.argv[1:], "ahn:rsgN:m:t:i:", ["gaIters=", "mimicIters=","gaPop=", "gaMate=", "gaMutate=", "mimicSamples=", "mimicToKeep=", "saTemp=", "saCooling="])
    except:
       print 'knapsack.py -i <iterations> -n <NUM_ITEMS> -c <COPIES_EACH> -w <MAX_WEIGHT> -v <MAX_VOLUME>'
       sys.exit(2)
    for opt, arg in opts:
       if opt == '-h':
          print 'knapsack.py -i <iterations> -n <NUM_ITEMS> -c <COPIES_EACH> -w <MAX_WEIGHT> -v <MAX_VOLUME>'
          sys.exit(1)
       elif opt == '-i':
          iterations = int(arg)
       elif opt == '-N':
          N = int(arg)
       elif opt == '-t':
           T = float(arg)
       elif opt == '-d':
          tempDenom = int(arg)
       elif opt == '-r':
           alg = 'RHC'
       elif opt == '-a':
           alg = 'all'
       elif opt == '-s':
           alg = 'SA'
       elif opt == '-g':
           alg = 'GA'
       elif opt == '-m':
           alg = 'MIMIC'
       elif opt == '--gaPop':
          gaPop = int(arg)
       elif opt == '--gaMate':
          gaMate = int(arg)
       elif opt == '--gaMutate':
          gaMutate = int(arg)
       elif opt == '--mimicSamples':
          mimicSamples = int(arg)
       elif opt == '--mimicToKeep':
          mimicToKeep = int(arg)
       elif opt == '--saTemp':
          saTemp = float(arg)
       elif opt == '--saCooling':
          saCooling = float(arg)
       elif opt == '--gaIters':
          gaIters = int(arg)
       elif opt == '--mimicIters':
          mimicIters = int(arg)
       elif opt == '-n':
           run = int(arg)


    vars = {
        'N':N,
        'tempDenom':tempDenom,
        'T':T,
        'fill':fill,
        'ranges':ranges,
        'iterations' :iterations,
        'gaIters':gaIters,
        'mimicIters':mimicIters,
        'gaPop' :gaPop,
        'gaMate' :gaMate,
        'gaMutate' :gaMutate,
        'mimicSamples' : mimicSamples,
        'mimicToKeep' : mimicToKeep,
        'saTemp' : saTemp,
        'saCooling' : saCooling,
        'alg' : alg,
        'run' : run
    }

    settings = getSettings(alg, settings, vars)

    T=N/tempDenom
    fill = [2] * N
    ranges = array('i', fill)

    ef = FourPeaksEvaluationFunction(T)
    odd = DiscreteUniformDistribution(ranges)
    nf = DiscreteChangeOneNeighbor(ranges)
    mf = DiscreteChangeOneMutation(ranges)
    cf = SingleCrossOver()
    df = DiscreteDependencyTree(.1, ranges)
    hcp = GenericHillClimbingProblem(ef, odd, nf)
    gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
    pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

    if alg == 'RHC' or alg == 'all':
        rhc = RandomizedHillClimbing(hcp)
        fit = FixedIterationTrainer(rhc, iterations)
        fit.train()
        rows = []
        row = []
        row.append("Evaluation Function Value")
        row.append(ef.value(rhc.getOptimal()))
        rows.append(row)
        print "RHC: " + str(ef.value(rhc.getOptimal()))
        output2('4Peaks', 'RHC', rows, settings)
        rows = []
        buildFooter("4Peaks", "RHC", rows, settings),
        outputFooter("4Peaks", "RHC", rows,   settings)

    if alg == 'SA' or alg == 'all':
        sa = SimulatedAnnealing(saTemp, saCooling, hcp)
        fit = FixedIterationTrainer(sa, iterations)
        fit.train()
        rows = []
        row = []
        row.append("Evaluation Function Value")
        row.append(ef.value(sa.getOptimal()))
        rows.append(row)
        print "SA: " + str(ef.value(sa.getOptimal()))
        output2('4Peaks', 'SA', rows, settings)
        rows = []
        buildFooter("4Peaks", "SA", rows, settings)
        outputFooter("4Peaks", "SA", rows, settings)

    if alg == 'GA' or alg == 'all':
        ga = StandardGeneticAlgorithm(gaPop, gaMate, gaMutate, gap)
        fit = FixedIterationTrainer(ga, gaIters)
        fit.train()
        print "GA: " + str(ef.value(ga.getOptimal()))
        rows = []
        row = []
        row.append("Evaluation Function Value")
        row.append(ef.value(ga.getOptimal()))
        rows.append(row)
        output2('4Peaks', 'GA', rows, settings)
        rows = []
        buildFooter("4Peaks", "GA", rows, settings)
        outputFooter("4Peaks", "GA", rows , settings)

    if alg == 'MIMIC' or alg == 'all':
        mimic = MIMIC(mimicSamples, mimicToKeep, pop)
        fit = FixedIterationTrainer(mimic, mimicIters)
        fit.train()
        print "MIMIC: " + str(ef.value(mimic.getOptimal()))
        rows = []
        row = []
        row.append("Evaluation Function Value")
        row.append(ef.value(mimic.getOptimal()))
        rows.append(row)
        output2('4Peaks', 'MIMIC', rows, settings)
        rows = []
        buildFooter("4Peaks", "GA", rows, settings)
        outputFooter("4Peaks", "MIMIC", rows, settings)
Exemplo n.º 12
0
def run_all_2(N=200,T=40,fout=None):
    problem = 'flipflop'
    # N=200
    # T=N/10
    maxEpochs = 10**5
    maxTime = 300 #5 minutes
    fill = [2] * N
    ranges = array('i', fill)

    # ef = FourPeaksEvaluationFunction(T)
    ef = FlipFlopEvaluationFunction()
    
    odd = DiscreteUniformDistribution(ranges)
    nf = DiscreteChangeOneNeighbor(ranges)
    mf = DiscreteChangeOneMutation(ranges)
    # mf = SwapMutation()
    cf = SingleCrossOver()
    df = DiscreteDependencyTree(.1, ranges)
    hcp = GenericHillClimbingProblem(ef, odd, nf)
    gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
    pop = GenericProbabilisticOptimizationProblem(ef, odd, df)
    

    def run_algo(alg,fit,label,difficulty,iters):
        trainTimes = [0.]
        trainTime = []
        scoreChange = [0.]
        stuckCount = 10**3
        prev = 0.
        for epoch in range(0,maxEpochs,1):
        
            st = time.clock()
            fit.train()
            et = time.clock()
            
            trainTimes.append(trainTimes[-1]+(et-st))
            trainTime.append((et-st))
            rollingMean = 10
            avgTime = (math.fsum(trainTime[-rollingMean:]) / float(rollingMean))
        
            score = ef.value(alg.getOptimal())
            # print(score,difficulty)
            
            # trialString = '{}-{}-{}-{}'.format(label,score,epoch,trainTimes[-1])
            trialData = [problem,difficulty,label,score,epoch,trainTimes[-1],avgTime,iters]
            print(trialData)
            # fout.writerow(trialData)
            
            optimum = (difficulty-1)
            if score >= optimum: break
            
            scoreChange.append(abs(score-prev))
            prev = score
            scoreChange = scoreChange[-stuckCount:]
            # print(scoreChange)
            if max(scoreChange) == 0: break
            
            if trainTimes[-1] > maxTime: break
            
    
        # print(trialData)
        fout.writerow(trialData)
        
        
    iters = 10
    rhc = RandomizedHillClimbing(hcp)
    fit = FixedIterationTrainer(rhc, iters)
    run_algo(rhc,fit,'RHC',N,iters)


    iters = 10
    startTemp = 1E10
    coolingFactor = .99
    sa = SimulatedAnnealing(startTemp, coolingFactor, hcp)
    fit = FixedIterationTrainer(sa, iters)
    run_algo(sa,fit,'SA',N,iters)

    iters = 10
    population = 300
    mates = 40
    mutations = 10
    ga = StandardGeneticAlgorithm(population, mates, mutations, gap)
    fit = FixedIterationTrainer(ga, iters)
    run_algo(ga,fit,'GA',N,iters)
    
    iters = 10
    samples = 200
    keep = 5
    mimic = MIMIC(samples, keep, pop)
    fit = FixedIterationTrainer(mimic, iters)
    run_algo(mimic,fit,'MIMIC',N,iters)
Exemplo n.º 13
0
n_iteration = 5000

sa_fitness = [[] for i in range(cycle)]
sa_training_time = [[] for i in range(cycle)]

for n in range(cycle):
    print("the %d th cycle" % (n + 1))

    ef = ContinuousPeaksEvaluationFunction(T)
    odd = DiscreteUniformDistribution(ranges)
    nf = DiscreteChangeOneNeighbor(ranges)
    hcp = GenericHillClimbingProblem(ef, odd, nf)

    for SA_TEMPERATURE in SA_TEMPERATURE_pool:
        sa = SimulatedAnnealing(SA_TEMPERATURE, SA_COOLING_FACTOR, hcp)
        fit_sa = FixedIterationTrainer(sa, n_iteration)

        print("calculating for temperature = %e" % SA_TEMPERATURE)

        # Training
        start_sa = time.time()
        fit_sa.train()
        end_sa = time.time()

        # Result extracting
        last_training_time_sa = end_sa - start_sa
        sa_training_time[n].append(last_training_time_sa)
        sa_fitness[n].append(ef.value(sa.getOptimal()))

overall_sa_training_time = list_avg(*sa_training_time)
overall_sa_fitness = list_avg(*sa_fitness)
Exemplo n.º 14
0
    mf = DiscreteChangeOneMutation(ranges)
    cf = UniformCrossOver()
    df = DiscreteDependencyTree(.1, ranges)
    hcp = GenericHillClimbingProblem(ef, odd, nf)
    gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
    pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

    # Algorithm declaration
    rhc = RandomizedHillClimbing(hcp)
    sa = SimulatedAnnealing(SA_TEMPERATURE, SA_COOLING_FACTOR, hcp)
    ga = StandardGeneticAlgorithm(GA_POPULATION, GA_CROSSOVER, GA_MUTATION,
                                  gap)
    mimic = MIMIC(MIMIC_SAMPLES, MIMIC_TO_KEEP, pop)

    # Trainer declaration
    fit_rhc = FixedIterationTrainer(rhc, current_iteration_count)
    fit_sa = FixedIterationTrainer(sa, current_iteration_count)
    fit_ga = FixedIterationTrainer(ga, current_iteration_count)
    fit_mimic = FixedIterationTrainer(mimic, current_iteration_count)

    print("Computing for %d iterations" % current_iteration_count)

    # Fitting
    start_rhc = time.time()
    fit_rhc.train()
    end_rhc = time.time()

    start_sa = time.time()
    fit_sa.train()
    end_sa = time.time()
Exemplo n.º 15
0
    rhc_total = 0
    rhc_time = 0

    for x in range(runs):
        ranges = array('i', [2] * N)
        fitness = ContinuousPeaksEvaluationFunction(T)
        discrete_dist = DiscreteUniformDistribution(ranges)
        discrete_neighbor = DiscreteChangeOneNeighbor(ranges)
        discrete_mutation = DiscreteChangeOneMutation(ranges)
        crossover = SCO()
        discrete_dependency = DiscreteDependencyTree(.1, ranges)
        hill_problem = GHC(fitness, discrete_dist, discrete_neighbor)

        start = time.clock()
        rhc_problem = RHC(hill_problem)
        fit = FixedIterationTrainer(rhc_problem, iteration)
        fit.train()
        end = time.clock()
        full_time = end - start
        rhc_total += fitness.value(rhc_problem.getOptimal())
        rhc_time += full_time

    rhc_total_avg = rhc_total / runs
    rhc_time_avg = rhc_time / runs

    data = '{},{},{}\n'.format(iteration, rhc_total_avg, rhc_time_avg)
    print(data)
    with open(output_directory, 'a') as f:
        f.write(data)

#SA
Exemplo n.º 16
0
def rhc_fac(args = {}):
    constant_params = {'hcp':hcp}
    params = merge_two_dicts(args, constant_params)
    print(params)
    rhc = RandomizedHillClimbing(hcp)
    return FixedIterationTrainer(rhc, num_iterations)
Exemplo n.º 17
0
def ga_fac(args = {}):
    constant_params = {'hcp':hcp}
    params = merge_two_dicts(args,constant_params)
    ga = StandardGeneticAlgorithm(args['populationSize'], int(args['populationSize'] * args['toMate']), int(args['populationSize'] * args['toMutate']), gap)
    gfit = FixedIterationTrainer(ga, num_iterations)
    return gfit
Exemplo n.º 18
0
ef = CountOnesEvaluationFunction()
odd = DiscreteUniformDistribution(ranges)
nf = DiscreteChangeOneNeighbor(ranges)
mf = DiscreteChangeOneMutation(ranges)
cf = SingleCrossOver()
df = DiscreteDependencyTree(.1, ranges)
hcp = GenericHillClimbingProblem(ef, odd, nf)
gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

t0 = time.time()
calls = []
results = []
for _ in range(runs):
    rhc = RandomizedHillClimbing(hcp)
    fit = FixedIterationTrainer(rhc, 200)
    fitness = fit.train()
    results.append(ef.value(rhc.getOptimal()))
    calls.append(ef.getTotalCalls())
    ef.clearCount()
print "RHC, average results , " + str(sum(results) / float(runs))
print "RHC, average feval calls , " + str(sum(calls) / float(runs))
t1 = time.time() - t0
print "RHC, average time , " + str(float(t1) / runs)

t0 = time.time()
calls = []
results = []
for _ in range(runs):
    sa = SimulatedAnnealing(1E11, .95, hcp)
    fit = FixedIterationTrainer(sa, 200)
Exemplo n.º 19
0
#           fevals = ef.fevals
            score = ef.value(ga.getOptimal())
#           ef.fevals -= 1
            st = '{},{},{}\n'.format(i,score,times[-1])
            print st
            with open(fname,'a') as f:
                f.write(st)
'''
#MIMIC
for t in range(numTrials):
    for samples, keep, m in product([100], [50], [0.1, 0.3, 0.5, 0.7, 0.9]):
        fname = outfile.replace('@ALG@', 'MIMIC{}_{}_{}'.format(
            samples, keep, m)).replace('@N@', str(t + 1))
        with open(fname, 'w') as f:
            f.write('iterations,fitness,time,fevals\n')
        mimic = MIMIC(samples, keep, pop)
        fit = FixedIterationTrainer(mimic, 10)
        times = [0]
        for i in range(0, maxIters, 10):
            start = clock()
            fit.train()
            elapsed = time.clock() - start
            times.append(times[-1] + elapsed)
            #           fevals = ef.fevals
            score = ef.value(mimic.getOptimal())
            #           ef.fevals -= 1
            st = '{},{},{}\n'.format(i, score, times[-1])
            print st
            with open(fname, 'a') as f:
                f.write(st)
Exemplo n.º 20
0
# print "Finished Simulated Annealing Seacrh."
# print "="*100
#"""

#=======================
# Genetic Algorithm
#=======================
print "Starting Genetic Algorithm Seacrh..."
ga = StandardGeneticAlgorithm(GA_popsize, GA_toMate, GA_toMutate, gap)
ga_iters = []
ga_fitness = []
ga_time = []

for i in maxiters_ga:
    fit = FixedIterationTrainer(ga, i)
    t1 = time.time()
    fit.train()
    t2 = time.time()
    fitness = ef.value(ga.getOptimal())
    time_ms = round(1000 * (t2 - t1), 2)
    ga_fitness.append(fitness)
    ga_time.append(time_ms)
    ga_iters.append(i)
    print "GA fitness using " + str(i) + " fixed iterations: " + str(fitness)
    print "Time taken for GA using fixed iterations: " + str(
        time_ms) + " milliseconds"

print "Finished Genetic Algorithm Seacrh."
print "=" * 100
"""
Exemplo n.º 21
0
# RHC
#############################################################
fname = outfile.replace('@ALG@', 'RHC')
with open(fname, 'w') as f:
    f.write('N,T,trial,iterations,fitness,time,fevals\n')
for N in range(N_min, N_max + 1, N_min):
    fill = [2] * N
    ranges = array('i', fill)
    T = 4 * N / 10
    for t in range(numTrials):
        ef = ContinuousPeaksEvaluationFunction(T)
        odd = DiscreteUniformDistribution(ranges)
        nf = DiscreteChangeOneNeighbor(ranges)
        hcp = GenericHillClimbingProblem(ef, odd, nf)
        rhc = RandomizedHillClimbing(hcp)
        fit = FixedIterationTrainer(rhc, increments)
        times = [0]
        lastScore = 0
        halt_count = 0
        total_iter = 0
        for i in range(0, maxIters, increments):
            start = clock()
            fit.train()
            elapsed = time.clock() - start
            times.append(times[-1] + elapsed)
            fevals = ef.fevals
            score = ef.value(rhc.getOptimal())
            ef.fevals -= 1
            st = '{},{},{},{},{},{},{},{}\n'.format(N, T, t, i, score, times[-1], fevals, halt_count)
            print st
            with open(fname, 'a') as f:
Exemplo n.º 22
0
    ef = MaxKColorFitnessFunction(vertices)
    odd = DiscretePermutationDistribution(K)
    nf = SwapNeighbor()
    mf = SwapMutation()
    cf = SingleCrossOver()

    hcp = GenericHillClimbingProblem(ef, odd, nf)
    gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)

    df = DiscreteDependencyTree(.1)
    pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

    start_time = time.time()
    rhc = RandomizedHillClimbing(hcp)
    fit = FixedIterationTrainer(rhc, 20000)
    fit.train()
    value = ef.value(rhc.getOptimal())
    stdout.write("RHC %s Value: %d. Time: %0.03f\n" % (ef.foundConflict(),
                                                     value, time.time() - start_time))

    data['RHC'][0] += value
    if ef.foundConflict() == "Found Max-K Color Combination !":
        data['RHC'][1] += 1

    start_time = time.time()
    sa = SimulatedAnnealing(1E12, .1, hcp)
    fit = FixedIterationTrainer(sa, 20000)
    fit.train()
    value = ef.value(sa.getOptimal())
    stdout.write("SA %s Value: %d. Time: %0.03f\n" % (ef.foundConflict(),
Exemplo n.º 23
0
def travelingsalesmanfunc(N, iterations):

    rhcMult = 1500
    saMult = 1500
    gaMult = 1
    mimicMult = 3

    random = Random()

    points = [[0 for x in xrange(2)] for x in xrange(N)]
    for i in range(0, len(points)):
        points[i][0] = random.nextDouble()
        points[i][1] = random.nextDouble()

    optimalOut = []
    timeOut = []
    evalsOut = []

    for niter in iterations:

        ef = TravelingSalesmanRouteEvaluationFunction(points)
        odd = DiscretePermutationDistribution(N)
        nf = SwapNeighbor()
        mf = SwapMutation()
        cf = TravelingSalesmanCrossOver(ef)
        hcp = GenericHillClimbingProblem(ef, odd, nf)
        gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)

        iterOptimalOut = [N, niter]
        iterTimeOut = [N, niter]
        iterEvals = [N, niter]

        start = time.time()
        rhc = RandomizedHillClimbing(hcp)
        fit = FixedIterationTrainer(rhc, niter * rhcMult)
        fit.train()
        end = time.time()
        rhcOptimal = ef.value(rhc.getOptimal())
        rhcTime = end - start
        print "RHC Inverse of Distance: optimum: " + str(rhcOptimal)
        print "RHC time: " + str(rhcTime)
        #print "RHC Inverse of Distance: " + str(ef.value(rhc.getOptimal()))
        print "Route:"
        path = []
        for x in range(0, N):
            path.append(rhc.getOptimal().getDiscrete(x))
        print path
        iterOptimalOut.append(rhcOptimal)
        iterTimeOut.append(rhcTime)
        functionEvals = ef.getNumEvals()
        ef.zeroEvals()
        iterEvals.append(functionEvals)

        start = time.time()
        sa = SimulatedAnnealing(1E12, .999, hcp)
        fit = FixedIterationTrainer(sa, niter * saMult)
        fit.train()
        end = time.time()
        saOptimal = ef.value(sa.getOptimal())
        saTime = end - start
        print "SA Inverse of Distance optimum: " + str(saOptimal)
        print "SA time: " + str(saTime)
        #print "SA Inverse of Distance: " + str(ef.value(sa.getOptimal()))
        print "Route:"
        path = []
        for x in range(0, N):
            path.append(sa.getOptimal().getDiscrete(x))
        print path
        iterOptimalOut.append(saOptimal)
        iterTimeOut.append(saTime)
        functionEvals = ef.getNumEvals()
        ef.zeroEvals()
        iterEvals.append(functionEvals)

        start = time.time()
        ga = StandardGeneticAlgorithm(2000, 1500, 250, gap)
        fit = FixedIterationTrainer(ga, niter * gaMult)
        fit.train()
        end = time.time()
        gaOptimal = ef.value(ga.getOptimal())
        gaTime = end - start
        print "GA Inverse of Distance optimum: " + str(gaOptimal)
        print "GA time: " + str(gaTime)
        #print "GA Inverse of Distance: " + str(ef.value(ga.getOptimal()))
        print "Route:"
        path = []
        for x in range(0, N):
            path.append(ga.getOptimal().getDiscrete(x))
        print path
        iterOptimalOut.append(gaOptimal)
        iterTimeOut.append(gaTime)
        functionEvals = ef.getNumEvals()
        ef.zeroEvals()
        iterEvals.append(functionEvals)

        start = time.time()
        # for mimic we use a sort encoding
        ef = TravelingSalesmanSortEvaluationFunction(points)
        fill = [N] * N
        ranges = array('i', fill)
        odd = DiscreteUniformDistribution(ranges)
        df = DiscreteDependencyTree(.1, ranges)
        pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

        start = time.time()
        mimic = MIMIC(500, 100, pop)
        fit = FixedIterationTrainer(mimic, niter * mimicMult)
        fit.train()
        end = time.time()
        mimicOptimal = ef.value(mimic.getOptimal())
        mimicTime = end - start
        print "MIMIC Inverse of Distance optimum: " + str(mimicOptimal)
        print "MIMIC time: " + str(mimicTime)
        #print "MIMIC Inverse of Distance: " + str(ef.value(mimic.getOptimal()))
        print "Route:"
        path = []
        optimal = mimic.getOptimal()
        fill = [0] * optimal.size()
        ddata = array('d', fill)
        for i in range(0, len(ddata)):
            ddata[i] = optimal.getContinuous(i)
        order = ABAGAILArrays.indices(optimal.size())
        ABAGAILArrays.quicksort(ddata, order)
        print order
        iterOptimalOut.append(mimicOptimal)
        iterTimeOut.append(mimicTime)
        functionEvals = ef.getNumEvals()
        ef.zeroEvals()
        iterEvals.append(functionEvals)

        optimalOut.append(iterOptimalOut)
        timeOut.append(iterTimeOut)
        evalsOut.append(iterEvals)

    return [optimalOut, timeOut, evalsOut]
Exemplo n.º 24
0
            st = '{},{},{}\n'.format(i,score,times[-1])
            print st
            with open(fname,'a') as f:
                f.write(st)
'''
# SA
for t in range(numTrials):
    for CE in [0.15, 0.35, 0.55, 0.75, 0.95]:
        fname = outfile.replace('@ALG@',
                                'SA{}'.format(CE)).replace('@N@', str(t + 1))
        with open(fname, 'w') as f:
            f.write('iterations,fitness,time,fevals\n')
        ef = TravelingSalesmanRouteEvaluationFunction(points)
        hcp = GenericHillClimbingProblem(ef, odd, nf)
        sa = SimulatedAnnealing(1E10, CE, hcp)
        fit = FixedIterationTrainer(sa, 10)
        times = [0]
        for i in range(0, maxIters, 10):
            start = clock()
            fit.train()
            elapsed = time.clock() - start
            times.append(times[-1] + elapsed)
            score = ef.value(sa.getOptimal())
            st = '{},{},{}\n'.format(i, score, times[-1])
            print st
            with open(fname, 'a') as f:
                f.write(st)
'''
#GA
for t in range(numTrials):
    for pop,mate,mutate in product([100],[50,30,10],[30,10]):
# create range
fill = [COPIES_EACH + 1] * N
ranges = array('i', fill)

ef = KnapsackEvaluationFunction(weights, volumes, KNAPSACK_VOLUME, copies)
odd = DiscreteUniformDistribution(ranges)
nf = DiscreteChangeOneNeighbor(ranges)
mf = DiscreteChangeOneMutation(ranges)
cf = UniformCrossOver()
df = DiscreteDependencyTree(.1, ranges)
hcp = GenericHillClimbingProblem(ef, odd, nf)
gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

# -- begin problem

t0 = time.time()
calls = []
results = []
for _ in range(runs):
    ga = StandardGeneticAlgorithm(ga_pop, ga_keep, ga_mut, gap)
    fit = FixedIterationTrainer(ga, 1000)
    fitness = fit.train()
    results.append(ef.value(ga.getOptimal()))
    calls.append(ef.getTotalCalls())
    ef.clearCount()
print "GA, average results , " + str(sum(results) / float(runs))
print "GA, average feval calls , " + str(sum(calls) / float(runs))
t1 = time.time() - t0
print "GA, average time , " + str(t1 / float(runs))
Exemplo n.º 26
0
def run_four_peaks():

    N = 200
    T = N / 5
    fill = [2] * N
    ranges = array('i', fill)

    ef = FourPeaksEvaluationFunction(T)
    odd = DiscreteUniformDistribution(ranges)
    nf = DiscreteChangeOneNeighbor(ranges)
    mf = DiscreteChangeOneMutation(ranges)
    cf = SingleCrossOver()
    df = DiscreteDependencyTree(.1, ranges)
    hcp = GenericHillClimbingProblem(ef, odd, nf)
    gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
    pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

    iters = [50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000]
    num_repeats = 5

    rhc_results = []
    rhc_times = []
    for i in iters:
        print(i)
        for j in range(num_repeats):
            start = time.time()
            rhc = RandomizedHillClimbing(hcp)
            fit = FixedIterationTrainer(rhc, i)
            fit.train()
            end = time.time()
            rhc_results.append(ef.value(rhc.getOptimal()))
            rhc_times.append(end - start)
            print "RHC: " + str(ef.value(rhc.getOptimal()))

    sa_results = []
    sa_times = []
    for i in iters:
        print(i)
        for j in range(num_repeats):
            start = time.time()
            sa = SimulatedAnnealing(1E11, .95, hcp)
            fit = FixedIterationTrainer(sa, i)
            fit.train()
            end = time.time()
            sa_results.append(ef.value(sa.getOptimal()))
            sa_times.append(end - start)
            print "SA: " + str(ef.value(sa.getOptimal()))

    ga_results = []
    ga_times = []
    for i in iters:
        print(i)
        for j in range(num_repeats):
            start = time.time()
            ga = StandardGeneticAlgorithm(200, 100, 10, gap)
            fit = FixedIterationTrainer(ga, i)
            fit.train()
            end = time.time()
            ga_results.append(ef.value(ga.getOptimal()))
            ga_times.append(end - start)
            print "GA: " + str(ef.value(ga.getOptimal()))

    mimic_results = []
    mimic_times = []
    for i in iters[0:6]:
        print(i)
        for j in range(num_repeats):
            start = time.time()
            mimic = MIMIC(200, 20, pop)
            fit = FixedIterationTrainer(mimic, i)
            fit.train()
            end = time.time()
            mimic_results.append(ef.value(mimic.getOptimal()))
            mimic_times.append(end - start)
            print "MIMIC: " + str(ef.value(mimic.getOptimal()))

    with open('four_peaks.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(rhc_results)
        writer.writerow(rhc_times)
        writer.writerow(sa_results)
        writer.writerow(sa_times)
        writer.writerow(ga_results)
        writer.writerow(ga_times)
        writer.writerow(mimic_results)
        writer.writerow(mimic_times)

    return rhc_results, rhc_times, sa_results, sa_times, ga_results, ga_times, mimic_results, mimic_times
Exemplo n.º 27
0
    volumes = array('d', fill)
    for i in range(0, NUM_ITEMS):
        weights[i] = random.nextDouble() * MAX_WEIGHT
        volumes[i] = random.nextDouble() * MAX_VOLUME

    fill = [COPIES_EACH + 1] * NUM_ITEMS
    ranges = array('i', fill)

    ef = KnapsackEvaluationFunction(weights, volumes, KNAPSACK_VOLUME, copies)
    odd = DiscreteUniformDistribution(ranges)
    df = DiscreteDependencyTree(.1, ranges)
    pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

    for MIMIC_SAMPLES in MIMIC_SAMPLES_pool:
        mimic = MIMIC(MIMIC_SAMPLES, MIMIC_TO_KEEP, pop)
        fit_mimic = FixedIterationTrainer(mimic, n_iteration)

        print("calculating for MIMIC_SAMPLES = %d" % MIMIC_SAMPLES)

        # Training
        start_mimic = time.time()
        fit_mimic.train()
        end_mimic = time.time()

        # Result extracting
        last_training_time_mimic = end_mimic - start_mimic
        mimic_training_time[n].append(last_training_time_mimic)
        mimic_fitness[n].append(ef.value(mimic.getOptimal()))

overall_mimic_training_time = list_avg(*mimic_training_time)
overall_mimic_fitness = list_avg(*mimic_fitness)
Exemplo n.º 28
0
def run_four_peaks_experiments():
    OUTPUT_DIRECTORY = './output'

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

    N = 200
    T = N / 5
    fill = [2] * N
    ranges = array('i', fill)
    ef = FourPeaksEvaluationFunction(T)
    odd = DiscreteUniformDistribution(ranges)
    nf = DiscreteChangeOneNeighbor(ranges)
    mf = DiscreteChangeOneMutation(ranges)
    cf = SingleCrossOver()
    hcp = GenericHillClimbingProblem(ef, odd, nf)
    gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
    max_iter = 5000
    outfile = OUTPUT_DIRECTORY + '/four_peaks_{}_log.csv'

    # Randomized Hill Climber
    filename = outfile.format('rhc')
    with open(filename, 'w') as f:
        f.write('iterations,fitness,time\n')
    for it in range(0, max_iter, 10):
        rhc = RandomizedHillClimbing(hcp)
        fit = FixedIterationTrainer(rhc, it)
        start_time = time.clock()
        fit.train()
        elapsed_time = time.clock() - start_time
        # fevals = ef.fevals
        score = ef.value(rhc.getOptimal())
        data = '{},{},{}\n'.format(it, score, elapsed_time)
        print(data)
        with open(filename, 'a') as f:
            f.write(data)

    # Simulated Annealing
    filename = outfile.format('sa')
    with open(filename, 'w') as f:
        f.write('iteration,cooling_value,fitness,elapsed_time\n')
    for cooling_value in (.19, .38, .76, .95):
        for it in range(0, max_iter, 10):
            sa = SimulatedAnnealing(1E11, cooling_value, hcp)
            fit = FixedIterationTrainer(sa, it)
            start_time = time.clock()
            fit.train()
            elapsed_time = time.clock() - start_time
            # fevals = ef.fevalss
            score = ef.value(sa.getOptimal())
            data = '{},{},{},{}\n'.format(it, cooling_value, score,
                                          elapsed_time)
            print(data)
            with open(filename, 'a') as f:
                f.write(data)

    # Genetic Algorithm
    filename = outfile.format('ga')
    with open(filename, 'w') as f:
        f.write('iteration,population_size,to_mate,to_mutate,fitness,time\n')
    for population_size, to_mate, to_mutate in itertools.product(
        [200], [25, 50, 75, 100], [10, 20, 30, 40]):
        for it in range(0, max_iter, 10):
            ga = StandardGeneticAlgorithm(population_size, to_mate, to_mutate,
                                          gap)
            fit = FixedIterationTrainer(ga, it)
            start_time = time.clock()
            fit.train()
            elapsed_time = time.clock() - start_time
            # fevals = ef.fevals
            score = ef.value(ga.getOptimal())
            data = '{},{},{},{},{},{}\n'.format(it, population_size, to_mate,
                                                to_mutate, score, elapsed_time)
            print(data)
            with open(filename, 'a') as f:
                f.write(data)

    # MIMIC
    filename = outfile.format('mm')
    with open(filename, 'w') as f:
        f.write('iterations,samples,to_keep,fitness,time\n')
    for samples, to_keep, m in itertools.product([200], [20],
                                                 [0.1, 0.3, 0.5, 0.7, 0.9]):
        for it in range(0, 500, 10):
            df = DiscreteDependencyTree(m, ranges)
            pop = GenericProbabilisticOptimizationProblem(ef, odd, df)
            mm = MIMIC(samples, 20, pop)
            fit = FixedIterationTrainer(mm, it)
            start_time = time.clock()
            fit.train()
            elapsed_time = time.clock() - start_time
            # fevals = ef.fevals
            score = ef.value(mm.getOptimal())
            data = '{},{},{},{},{},{}\n'.format(it, samples, to_keep, m, score,
                                                elapsed_time)
            print(data)
            with open(filename, 'a') as f:
                f.write(data)
Exemplo n.º 29
0
print("N: " + str(N))

ef = CountOnesEvaluationFunction()
odd = DiscreteUniformDistribution(ranges)
nf = DiscreteChangeOneNeighbor(ranges)
mf = DiscreteChangeOneMutation(ranges)
cf = SingleCrossOver()
df = DiscreteDependencyTree(.1, ranges)
hcp = GenericHillClimbingProblem(ef, odd, nf)
gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

start = time.time()
rhc = RandomizedHillClimbing(hcp)
rhcIterations = 100
fit = FixedIterationTrainer(rhc, rhcIterations)
fit.train()
print("\nRHC: " + str(ef.value(rhc.getOptimal())))
print("RHC Iterations: " + str(rhcIterations))
end = time.time()
traintime = end - start
print("RHC results time: %0.03f seconds" % (traintime,))

start = time.time()
sa = SimulatedAnnealing(100, .95, hcp)
saIterations = 200
fit = FixedIterationTrainer(sa, saIterations)
fit.train()
print("\nSA: " + str(ef.value(sa.getOptimal())))
print("SA Iterations: " + str(saIterations))
end = time.time()
Exemplo n.º 30
0
    fill = [COPIES_EACH + 1] * NUM_ITEMS
    ranges = array('i', fill)

    ef = KnapsackEvaluationFunction(weights, volumes, KNAPSACK_VOLUME, copies)
    odd = DiscreteUniformDistribution(ranges)
    nf = DiscreteChangeOneNeighbor(ranges)
    mf = DiscreteChangeOneMutation(ranges)
    cf = UniformCrossOver()
    df = DiscreteDependencyTree(.1, ranges)
    hcp = GenericHillClimbingProblem(ef, odd, nf)
    gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
    pop = GenericProbabilisticOptimizationProblem(ef, odd, df)
    expt = "expt_avg"

    rhc = RandomizedHillClimbing(hcp)
    fit = FixedIterationTrainer(rhc, 200000)
    score_RHC.append(train(rhc, "RHC", ef, 200000, "test", expt))
    print "RHC Inverse of Distance: " + str(ef.value(rhc.getOptimal()))

    sa = SimulatedAnnealing(1E9, .95, hcp)
    score_SA.append(train(sa, "SA", ef, 200000, "test", expt))
    print "SA Inverse of Distance: " + str(ef.value(sa.getOptimal()))

    ga = StandardGeneticAlgorithm(300, 80, 5, gap)
    score_GA.append(train(ga, "GA", ef, 40000, "test", expt))
    print "GA Inverse of Distance: " + str(ef.value(ga.getOptimal()))

    mimic = MIMIC(250, 10, pop)
    score_MIMIC.append(train(mimic, "MIMIC", ef, 4000, "test", expt))
    print "MIMIC Inverse of Distance: " + str(ef.value(mimic.getOptimal()))
Exemplo n.º 31
0
        # fit = FixedIterationTrainer(sa, it_count)
        # fit.train()
        # value = ef.value(sa.getOptimal())
        # print "SA: " + str(ef.value(sa.getOptimal()))



        # ga = StandardGeneticAlgorithm(param[0], param[1], param[2], gap)
        # fit = FixedIterationTrainer(ga, it_count)
        # fit.train()
        # value = ef.value(ga.getOptimal())
        # # print "GA: " + str(ef.value(ga.getOptimal()))

        start = time.time()
        mimic = MIMIC(param[0], param[1], pop)
        fit = FixedIterationTrainer(mimic, it_count)
        fit.train()
        value = ef.value(mimic.getOptimal())
        # print "MIMIC: " + str(ef.value(mimic.getOptimal()))

        end = time.time()
        results = {
            'num_iterations': it_count,
            'value': value,
            'time': end - start
        }
        print 'MIMIC', param, results
        writer.writerow(results)
    csv_file.close()
    print '------'
print '***** ***** ***** ***** *****'
Exemplo n.º 32
0
        odd = DiscreteUniformDistribution(ranges)
        nf = DiscreteChangeOneNeighbor(ranges)
        mf = DiscreteChangeOneMutation(ranges)
        cf = UniformCrossOver()
        df = DiscreteDependencyTree(.1, ranges)
        hcp = GenericHillClimbingProblem(ef, odd, nf)
        gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
        pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

        # rhc = RandomizedHillClimbing(hcp)
        # fit = FixedIterationTrainer(rhc, num_iterations)
        # fit.train()

        start = time.time()
        sa = SimulatedAnnealing(param[0], param[1], hcp)
        fit = FixedIterationTrainer(sa, num_iterations)
        fit.train()
        end = time.time()
        value = str(ef.value(sa.getOptimal()))
        results = {
            'num_iterations': num_iterations,
            'value': value,
            'time': end - start
        }
        print 'SA', param, results
        writer.writerow(results)

        # ga = StandardGeneticAlgorithm(param[0], param[1], param[2], gap)
        # fit = FixedIterationTrainer(ga, num_iterations)
        # fit.train()
        # print "GA: " + str(ef.value(ga.getOptimal()))
Exemplo n.º 33
0
df = DiscreteDependencyTree(.1, ranges)
hcp = GenericHillClimbingProblem(ef, odd, nf)
gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

iterations = range(100, 50000, 100)
rhc_results = []
sa_results = []
ga_results = []

import time

rhc_startTime = time.time()
for iteration in iterations:
    rhc = RandomizedHillClimbing(hcp)
    fit = FixedIterationTrainer(rhc, iteration)
    fit.train()
    rhc_optimalVal = ef.value(rhc.getOptimal())
    # print "RHC: " + str(rhc_optimalVal)
    rhc_results.append(rhc_optimalVal)
rhc_endTime = time.time()
print "RHC Completed in: " + str(rhc_endTime - rhc_startTime)

sa_startTime = time.time()
for iteration in iterations:
    sa = SimulatedAnnealing(1E11, .95, hcp)
    fit = FixedIterationTrainer(sa, iteration)
    fit.train()
    sa_optimalVal = ef.value(sa.getOptimal())
    # print "SA: " + str(sa_optimalVal)
    sa_results.append(sa_optimalVal)
Exemplo n.º 34
0
def fourpeaksfunc(N, iterations):

    rhcMult = 200
    saMult = 200
    gaMult = 2
    mimicMult = 1

    optimalOut = []
    timeOut = []
    evalsOut = []

    T = N / 5
    fill = [2] * N
    ranges = array('i', fill)

    ef = FourPeaksEvaluationFunction(T)
    odd = DiscreteUniformDistribution(ranges)
    nf = DiscreteChangeOneNeighbor(ranges)
    mf = DiscreteChangeOneMutation(ranges)
    cf = SingleCrossOver()
    df = DiscreteDependencyTree(.1, ranges)
    hcp = GenericHillClimbingProblem(ef, odd, nf)
    gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
    pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

    for niter in iterations:

        iterOptimalOut = [N, niter]
        iterTimeOut = [N, niter]
        iterEvals = [N, niter]

        start = time.time()
        rhc = RandomizedHillClimbing(hcp)
        fit = FixedIterationTrainer(rhc, niter * rhcMult)
        fit.train()
        end = time.time()
        rhcOptimal = ef.value(rhc.getOptimal())
        rhcTime = end - start
        print "RHC optimum: " + str(rhcOptimal)
        print "RHC time: " + str(rhcTime)
        iterOptimalOut.append(rhcOptimal)
        iterTimeOut.append(rhcTime)
        functionEvals = ef.getNumEvals()
        ef.zeroEvals()
        iterEvals.append(functionEvals)

        start = time.time()
        sa = SimulatedAnnealing(1E20, .8, hcp)
        fit = FixedIterationTrainer(sa, niter * saMult)
        fit.train()
        end = time.time()
        saOptimal = ef.value(sa.getOptimal())
        saTime = end - start
        print "SA optimum: " + str(saOptimal)
        print "SA time: " + str(saTime)
        iterOptimalOut.append(saOptimal)
        iterTimeOut.append(saTime)
        functionEvals = ef.getNumEvals()
        ef.zeroEvals()
        iterEvals.append(functionEvals)

        start = time.time()
        ga = StandardGeneticAlgorithm(200, 100, 10, gap)
        fit = FixedIterationTrainer(ga, niter * gaMult)
        fit.train()
        end = time.time()
        gaOptimal = ef.value(ga.getOptimal())
        gaTime = end - start
        print "GA optimum: " + str(gaOptimal)
        print "GA time: " + str(gaTime)
        iterOptimalOut.append(gaOptimal)
        iterTimeOut.append(gaTime)
        functionEvals = ef.getNumEvals()
        ef.zeroEvals()
        iterEvals.append(functionEvals)

        start = time.time()
        mimic = MIMIC(200, 20, pop)
        fit = FixedIterationTrainer(mimic, niter * mimicMult)
        fit.train()
        end = time.time()
        mimicOptimal = ef.value(mimic.getOptimal())
        mimicTime = end - start
        print "MIMIC optimum: " + str(mimicOptimal)
        print "MIMIC time: " + str(mimicTime)
        iterOptimalOut.append(mimicOptimal)
        iterTimeOut.append(mimicTime)
        functionEvals = ef.getNumEvals()
        ef.zeroEvals()
        iterEvals.append(functionEvals)

        optimalOut.append(iterOptimalOut)
        timeOut.append(iterTimeOut)
        evalsOut.append(iterEvals)

    return [optimalOut, timeOut, evalsOut]
Exemplo n.º 35
0
def run_knapsack_experiments():
    OUTPUT_DIRECTORY = './output'
    # Random number generator */
    random = Random()
    # The number of items
    NUM_ITEMS = 40
    # The number of copies each
    COPIES_EACH = 4
    # The maximum weight for a single element
    MAX_WEIGHT = 50
    # The maximum volume for a single element
    MAX_VOLUME = 50
    # The volume of the knapsack
    KNAPSACK_VOLUME = MAX_VOLUME * NUM_ITEMS * COPIES_EACH * .4

    # create copies
    fill = [COPIES_EACH] * NUM_ITEMS
    copies = array('i', fill)

    # create weights and volumes
    fill = [0] * NUM_ITEMS
    weights = array('d', fill)
    volumes = array('d', fill)
    for i in range(0, NUM_ITEMS):
        weights[i] = random.nextDouble() * MAX_WEIGHT
        volumes[i] = random.nextDouble() * MAX_VOLUME

    # create range
    fill = [COPIES_EACH + 1] * NUM_ITEMS
    ranges = array('i', fill)

    ef = KnapsackEvaluationFunction(weights, volumes, KNAPSACK_VOLUME, copies)
    odd = DiscreteUniformDistribution(ranges)
    nf = DiscreteChangeOneNeighbor(ranges)
    mf = DiscreteChangeOneMutation(ranges)
    cf = UniformCrossOver()
    hcp = GenericHillClimbingProblem(ef, odd, nf)
    gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
    max_iter = 5000
    outfile = OUTPUT_DIRECTORY + '/knapsack_{}_log.csv'

    # Randomized Hill Climber
    filename = outfile.format('rhc')
    with open(filename, 'w') as f:
        f.write('iterations,fitness,time\n')
    for it in range(0, max_iter, 10):
        rhc = RandomizedHillClimbing(hcp)
        fit = FixedIterationTrainer(rhc, it)
        start_time = time.clock()
        fit.train()
        elapsed_time = time.clock() - start_time
        # fevals = ef.fevals
        score = ef.value(rhc.getOptimal())
        data = '{},{},{}\n'.format(it, score, elapsed_time)
        print(data)
        with open(filename, 'a') as f:
            f.write(data)

    # Simulated Annealing
    filename = outfile.format('sa')
    with open(filename, 'w') as f:
        f.write('iteration,cooling_value,fitness,time\n')
    for cooling_value in (.19, .38, .76, .95):
        for it in range(0, max_iter, 10):
            sa = SimulatedAnnealing(200, cooling_value, hcp)
            fit = FixedIterationTrainer(sa, it)
            start_time = time.clock()
            fit.train()
            elapsed_time = time.clock() - start_time
            # fevals = ef.fevals
            score = ef.value(sa.getOptimal())
            data = '{},{},{},{}\n'.format(it, cooling_value, score,
                                          elapsed_time)
            print(data)
            with open(filename, 'a') as f:
                f.write(data)

    # Genetic Algorithm
    filename = outfile.format('ga')
    with open(filename, 'w') as f:
        f.write('iteration,population_size,to_mate,to_mutate,fitness,time\n')
    for population_size, to_mate, to_mutate in itertools.product(
        [200], [110, 120, 130, 140, 150], [2, 4, 6, 8]):
        for it in range(0, max_iter, 10):
            ga = StandardGeneticAlgorithm(population_size, to_mate, to_mutate,
                                          gap)
            fit = FixedIterationTrainer(ga, it)
            start_time = time.clock()
            fit.train()
            elapsed_time = time.clock() - start_time
            # fevals = ef.fevals
            score = ef.value(ga.getOptimal())
            data = '{},{},{},{},{},{}\n'.format(it, population_size, to_mate,
                                                to_mutate, score, elapsed_time)
            print(data)
            with open(filename, 'a') as f:
                f.write(data)

    # MIMIC
    filename = outfile.format('mm')
    with open(filename, 'w') as f:
        f.write('iterations,samples,to_keep,m,fitness,time\n')
    for samples, to_keep, m in itertools.product([200], [100],
                                                 [0.1, 0.3, 0.5, 0.7, 0.9]):
        for it in range(0, 500, 10):
            df = DiscreteDependencyTree(m, ranges)
            pop = GenericProbabilisticOptimizationProblem(ef, odd, df)
            mm = MIMIC(samples, 20, pop)
            fit = FixedIterationTrainer(mm, it)
            start_time = time.clock()
            fit.train()
            elapsed_time = time.clock() - start_time
            # fevals = ef.fevals
            score = ef.value(mm.getOptimal())
            data = '{},{},{},{},{},{}\n'.format(it, samples, to_keep, m, score,
                                                elapsed_time)
            print(data)
            with open(filename, 'a') as f:
                f.write(data)
# learn weigths with back propagation
network_bp = factory.createClassificationNetwork([inputLayer, hiddenLayer, outputLayer])
bp = BatchBackPropagationTrainer(set, network_bp, measure, RPROPUpdateRule())
cvt = ConvergenceTrainer(bp)
cvt.train()
print "\nBP training error:", errorRate(network_bp, train)
print "BP training confusion matrix:", confusionMatrix(network_bp, train)
print "    BP test error:", errorRate(network_bp, test)
print "    BP test confusion matrix:", confusionMatrix(network_bp, test)

# learn weights with randomized hill climbing
network_rhc = factory.createClassificationNetwork([inputLayer, hiddenLayer, outputLayer])
nnop_rhc = NeuralNetworkOptimizationProblem(set, network_rhc, measure)
rhc = RandomizedHillClimbing(nnop_rhc)
fit = FixedIterationTrainer(rhc, it_rhc)
fit.train()
op = rhc.getOptimal();
network_rhc.setWeights(op.getData())
print "\nRHC training error:", errorRate(network_rhc, train)
print "RHC training confusion matrix:", confusionMatrix(network_rhc, train)
print "    RHC test error:", errorRate(network_rhc, test)
print "    RHC test confusion matrix:", confusionMatrix(network_rhc, test)

# learn weights with simulated annealing
network_sa = factory.createClassificationNetwork([inputLayer, hiddenLayer, outputLayer])
nnop_sa = NeuralNetworkOptimizationProblem(set, network_sa, measure)
sa = SimulatedAnnealing(1E11, 0.95, nnop_sa)
fit = FixedIterationTrainer(sa, it_sa)
fit.train()
op = sa.getOptimal();
Exemplo n.º 37
0
        # fit = FixedIterationTrainer(rhc, it_count)
        # fit.train()

        # print "Time -->", end - start

        # print "RHC: " + str(value)

        # sa = SimulatedAnnealing(param[0], param[1], hcp)
        # fit = FixedIterationTrainer(sa, it_count)
        # fit.train()
        # value = ef.value(sa.getOptimal())
        # print "SA: " + str(ef.value(sa.getOptimal()))

        start = time.time()
        ga = StandardGeneticAlgorithm(param[0], param[1], param[2], gap)
        fit = FixedIterationTrainer(ga, it_count)
        fit.train()
        value = ef.value(ga.getOptimal())
        # print "GA: " + str(ef.value(ga.getOptimal()))
        end = time.time()
        results = {
            'num_iterations': it_count,
            'value': value,
            'time': end - start
        }
        print 'GA', param, results
        writer.writerow(results)
        # mimic = MIMIC(200, 20, pop)
        # fit = FixedIterationTrainer(mimic, it_count)
        # fit.train()
        # print "MIMIC: " + str(ef.value(mimic.getOptimal()))
Exemplo n.º 38
0
def main():

    # The number of items
    NUM_ITEMS = 40
    # The number of copies each
    COPIES_EACH = 4
    # The maximum weight for a single element
    MAX_WEIGHT = 50
    # The maximum volume for a single element
    MAX_VOLUME = 50

    iterations = 20000
    gaIters = 1000
    mimicIters = 1000
    gaPop = 200
    gaMate = 150
    gaMutate = 25
    mimicSamples = 200
    mimicToKeep = 100
    saTemp = 100
    saCooling = .95
    alg = 'all'
    run = 0
    settings = []

    try:
        opts, args = getopt.getopt(sys.argv[1:], "ahrsgmn:N:c:w:v:i:", ["gaIters=", "mimicIters=","gaPop=", "gaMate=", "gaMutate=", "mimicSamples=", "mimicToKeep=", "saTemp=", "saCooling="])
    except:
        print 'knapsack.py -i <iterations> -n <NUM_ITEMS> -c <COPIES_EACH> -w <MAX_WEIGHT> -v <MAX_VOLUME>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'knapsack.py -i <iterations> -n <NUM_ITEMS> -c <COPIES_EACH> -w <MAX_WEIGHT> -v <MAX_VOLUME>'
            sys.exit(1)
        elif opt == '-i':
            iterations = int(arg)
        elif opt == '-N':
            NUM_ITEMS = int(arg)
        elif opt == '-c':
            COPIES_EACH = int(arg)
        elif opt == '-w':
            MAX_WEIGHT = int(arg)
        elif opt == '-v':
            MAX_VOLUME = int(arg)
        elif opt == '-n':
            run = int(arg)
        elif opt == '-r':
            alg = 'RHC'
        elif opt == '-s':
            alg = 'SA'
        elif opt == '-g':
            alg = 'GA'
        elif opt == '-m':
            alg = 'MIMIC'
        elif opt == '-a':
            alg = 'all'
        elif opt == '--gaPop':
            gaPop = int(arg)
        elif opt == '--gaMate':
            gaMate = int(arg)
        elif opt == '--gaMutate':
            gaMutate = int(arg)
        elif opt == '--mimicSamples':
            mimicSamples = int(arg)
        elif opt == '--mimicToKeep':
            mimicToKeep = int(arg)
        elif opt == '--saTemp':
            saTemp = float(arg)
        elif opt == '--saCooling':
            saCooling = float(arg)
        elif opt == '--gaIters':
            gaIters = int(arg)
        elif opt == '--mimicIters':
            mimicIters = int(arg)
    vars ={
    'NUM_ITEMS' : NUM_ITEMS,
    'COPIES_EACH' : COPIES_EACH,
    'MAX_WEIGHT' : MAX_WEIGHT,
    'MAX_VOLUME' : MAX_VOLUME,
    'iterations' : iterations,
    'gaIters' : gaIters,
    'mimicIters' : mimicIters,
    'gaPop' : gaPop,
    'gaMate' : gaMate,
    'gaMutate' : gaMutate,
    'mimicSamples' : mimicSamples,
    'mimicToKeep' : mimicToKeep,
    'saTemp' : saTemp,
    'saCooling' : saCooling,
    'alg' : alg,
    'run' : run
    }

    settings = getSettings(alg, settings, vars)
    # Random number generator */
    random = Random()

    # The volume of the knapsack
    KNAPSACK_VOLUME = MAX_VOLUME * NUM_ITEMS * COPIES_EACH * .4

    # create copies
    fill = [COPIES_EACH] * NUM_ITEMS
    copies = array('i', fill)

    # create weights and volumes
    fill = [0] * NUM_ITEMS
    weights = array('d', fill)
    volumes = array('d', fill)
    for i in range(0, NUM_ITEMS):
        weights[i] = random.nextDouble() * MAX_WEIGHT
        volumes[i] = random.nextDouble() * MAX_VOLUME


    # create range
    fill = [COPIES_EACH + 1] * NUM_ITEMS
    ranges = array('i', fill)

    ef = KnapsackEvaluationFunction(weights, volumes, KNAPSACK_VOLUME, copies)
    odd = DiscreteUniformDistribution(ranges)
    nf = DiscreteChangeOneNeighbor(ranges)
    mf = DiscreteChangeOneMutation(ranges)
    cf = UniformCrossOver()
    df = DiscreteDependencyTree(.1, ranges)
    hcp = GenericHillClimbingProblem(ef, odd, nf)
    gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)
    pop = GenericProbabilisticOptimizationProblem(ef, odd, df)

    if alg == 'RHC' or alg == 'all':
        rhc = RandomizedHillClimbing(hcp)
        fit = FixedIterationTrainer(rhc, iterations)
        fit.train()
        print "RHC: " + str(ef.value(rhc.getOptimal()))
        rows = []
        row = []
        row.append("Evaluation Function Value")
        row.append(str(ef.value(rhc.getOptimal())))
        rows.append(row)
        output2('Knapsack', 'RHC', rows, settings)
        rows = []
        buildFooter("Knapsack", "RHC", rows, settings)
        outputFooter("Knapsack", "RHC", rows , settings)
    if alg == 'SA' or alg == 'all':
        sa = SimulatedAnnealing(saTemp, saCooling, hcp)
        fit = FixedIterationTrainer(sa, iterations)
        fit.train()
        rows = []
        row = []
        row.append("Evaluation Function Value")
        row.append(ef.value(sa.getOptimal()))
        rows.append(row)
        print "SA: " + str(ef.value(sa.getOptimal()))
        output2('Knapsack', 'SA', rows, settings)
        rows = []
        buildFooter("Knapsack", "SA", rows, settings)
        outputFooter("Knapsack", "SA", rows, settings)
    if alg == 'GA' or alg == 'all':
        ga = StandardGeneticAlgorithm(gaPop, gaMate, gaMutate, gap)
        fit = FixedIterationTrainer(ga, gaIters)
        fit.train()
        rows = []
        row = []
        row.append("Evaluation Function Value")
        row.append(ef.value(ga.getOptimal()))
        rows.append(row)
        print "GA: " + str(ef.value(ga.getOptimal()))
        output2('Knapsack', 'GA', rows, settings)
        buildFooter("Knapsack", "GA", rows, settings)
        outputFooter("Knapsack", "GA", rows , settings)
    if alg == 'MIMIC' or alg == 'all':
        mimic = MIMIC(mimicSamples, mimicToKeep, pop)
        fit = FixedIterationTrainer(mimic, mimicIters)
        fit.train()
        print "MIMIC: " + str(ef.value(mimic.getOptimal()))
        rows = []
        row = []
        row.append("Evaluation Function Value")
        row.append(ef.value(mimic.getOptimal()))
        rows.append(row)
        output2('Knapsack', 'MIMIC', rows, settings)
        rows = []
        buildFooter("Knapsack", "MIMIC", rows, settings)
        outputFooter("Knapsack", "MIMIC", rows , settings)
Exemplo n.º 39
0
    points[i][1] = random.nextDouble()

ef = TravelingSalesmanRouteEvaluationFunction(points)
odd = DiscretePermutationDistribution(N)
nf = SwapNeighbor()
mf = SwapMutation()
cf = TravelingSalesmanCrossOver(ef)
hcp = GenericHillClimbingProblem(ef, odd, nf)
gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)

iters_list = [100, 500, 1000, 2500, 5000, 7500, 10000, 20000]

print "Random Hill Climb"
rhc = RandomizedHillClimbing(hcp)
for iters in iters_list:
    fit = FixedIterationTrainer(rhc, iters)
    start = time.time()
    fit.train()
    dur = time.time() - start
    print "Iters: " + str(iters) + ", Fitness: " + str(
        ef.value(rhc.getOptimal())) + ", Dur: " + str(dur)
# print "Route:"
# path = []
# for x in range(0,N):
#     path.append(rhc.getOptimal().getDiscrete(x))
# print path

print "Simulated Annealing"
# 1e13, 0.8, 1e12 0.85, ... dang
temp = 1E13
cooling_rate = 0.90