def experiment1(self): l = GA(self.fitnessFunction, self.myNetwork.params[self.indices]) l.minimize = False l.verbose = True l.maxLearningSteps = 500 params, fitness = l.learn() self.myNetwork.params[self.indices] = params self.metaInfo["numsteps"] = l.maxLearningSteps self.metaInfo["fitness"] = fitness # self.myNetwork._setParameters(self.originalWeights) self.logNet()
def GA_minimize(function, guess): result = GA(function,[guess, ], minimize=True) # set to minimize by default start = timeit.default_timer() mem = max(memory_usage((result.learn,(),))) stop = timeit.default_timer() print result.learn() #Comment this out for faster performance, i.e. if used purely for evaluation exec_time = stop-start print '{0} took {1} seconds'.format('Genetic Algorithm',exec_time) print '{0} used {1} megabytes'.format('Genetic Algorithm',mem) print
def GA_minimize(function, guess): """ This function runs the genetic algorithm from PyBrain (http://pybrain.org/docs/api/optimization/optimization.html) on a function, provided with an initial guess. | NOTE: Format is **crucial** here or this will not work (blame the authors of PyBrain, sorry): | Function must take a **tuple** (**Even** if of only one element (in the form (a, )) and guess **MUST BE A LIST** (even if only with one element) """ result = GA(function, guess, minimize=True) # set to minimize by default start = timeit.default_timer() mem = max(memory_usage(-1,interval=.1)) print "The result is: ", result.learn() stop = timeit.default_timer() exec_time = stop-start print '{0} took {1} seconds'.format('Genetic Algorithm',exec_time) print '{0} used {1} megabytes'.format('Genetic Algorithm',mem) print
# -*- coding: utf-8 -*- """ Created on Thu Mar 7 20:41:24 2013 Just to try and get things working with a GA @author: david """ from pybrain.tools.shortcuts import buildNetwork from pybrain.structure.parametercontainer import ParameterContainer from pybrain.rl.environments.functions.unimodal import TabletFunction from pybrain.rl.environments.cartpole.balancetask import BalanceTask, CartPoleEnvironment from pybrain.optimization import GA from pybrain.rl.agents import LearningAgent, OptimizationAgent environment = CartPoleEnvironment() task = BalanceTask() nn = buildNetwork(task.outdim, 6, task.indim) learning_agent = OptimizationAgent(nn, GA())
def update(): """Opens file browser and gets selection""" name = tkFileDialog.askopenfilename() """Creates model for data""" if 'xml' in name: model = strainmodel(name, type='xml') else: model = strainmodel(name) data = model.get_experimental_data() """Will need to be set to user-input guess""" guess = [-150, 1] yieldpoint = None """Gets radio button input as to which method to use to optimize""" if yield_method.get() == 1: yieldpoint = material_analytics.yield_stress_classic_unfitted(data) elif yield_method.get() == 2: yieldpoint = material_analytics.yield_stress_classic_fitted(data) elif yield_method.get() == 3: yieldpoint = material_analytics.yield_stress(data) else: elastic, plastic = material_analytics.kmeanssplit(data) yieldpoint = plastic[0][None, ] """Displays the found yield stress""" plot.plotmult2D(data, yieldpoint, title='File', xtitle='Strain ($\epsilon$)', ytitle='Stress ($\sigma$)') """[0,1] is the first row, second column, which is the stress values""" SS_stress = yieldpoint[0, 1] model_training_methods = [ 'Nelder-Mead', 'Powell', 'CG', 'Newton-CG', 'BFGS', 'L-BFGS-B', 'SLSQP', 'COBYLA', 'TNC', 'Basinhopping', 'Brute Force', 'Genetic Algorithm' ] """Because basinhopping, brute force, and GA are all in separate libraries, they are handled as separate cases.""" optmethod = optimization_method.get() - 1 if optmethod < 9: model_params = optimization_suite.minimize_suite( model.mcfunc, methods=[ model_training_methods[optmethod], ], guess=guess, SS_stress=SS_stress) elif optmethod == 9: model_params = optimization_suite.minimize_suite(model.mcfunc, methods=[ basinhopping, ], guess=guess, SS_stress=SS_stress) elif optmethod == 10: model_params = optimization_suite.minimize_suite(model.mcfunc, methods=[ brute, ], guess=guess, SS_stress=SS_stress) else: model_params = GA(model.mcfunc, guess, minimize=True).learn() """Plots the data versus the fitted irreversible model data""" plot.plotmult2D(data, model.irreversible_model(model_params, SS_stress), title='Fitted Thermodynamics', xtitle='Strain ($\epsilon$)', ytitle='Stress ($\sigma$)')
def GA_Factory(): return GA()
for x in range(0,numberOfAgents): popList.append(initPopulation) for x in range(0,numberOfAgents): weights = initPopulation[0] NNetListParams.append(weights) i = 0 while (i < 50): for x in range(0,len(NNetListParams)): for k in range(0,len(NNetListParams)): NNetList[k]._setParameters(NNetListParams[k]) workingNN = x ga = GA(evaluator,NNetListParams[x],maxEvaluations = 20,initRangeScaling = 2,elitism = False,populationSize = populationSize,initialPopulation = popList[x],mutationProb = 0.1) ga.minimize = True result = ga.learn() NNetListParams[x] = result[0] popList[x] = ga.currentpop i += 1 print i for x in range(0,len(NNetListParams)): for k in range(0,len(NNetListParams)): NNetList[k]._setParameters(NNetListParams[k])