Using the Genetic Algorithm from the Command Line

Running ga with the Default Options

To run the genetic algorithm with the default options, call ga with the syntax

[x fval] = ga(@fitnessfun, nvars)

The input arguments to ga are

The output arguments are

For a description of additional input and output arguments, see the reference page for ga.

You can run the example described in Example: Rastrigin's Function from the command line by entering

[x fval] = ga(@rastriginsfcn, 2)

This returns

x =
    0.0027   -0.0052


fval =
    0.0068

Additional Output Arguments

To get more information about the performance of the genetic algorithm, you can call ga with the syntax

[x fval exitflag output population scores] = ga(@fitnessfcn, nvars)

Besides x and fval, this function returns the following additional output arguments:

See the ga reference page for more information about these arguments.

Setting Options for ga at the Command Line

You can specify any of the options that are available for ga by passing an options structure as an input argument to ga using the syntax

[x fval] = ga(@fitnessfun, nvars, [],[],[],[],[],[],[],options)

This syntax does not specify any linear equality, linear inequality, or nonlinear constraints.

You create the options structure using the function gaoptimset.

options = gaoptimset(@ga)

This returns the structure options with the default values for its fields.

options = 
        PopulationType: 'doubleVector'
          PopInitRange: [2x1 double]
        PopulationSize: 20
            EliteCount: 2
     CrossoverFraction: 0.8000
        ParetoFraction: []
    MigrationDirection: 'forward'
     MigrationInterval: 20
     MigrationFraction: 0.2000
           Generations: 100
             TimeLimit: Inf
          FitnessLimit: -Inf
         StallGenLimit: 50
        StallTimeLimit: Inf
                TolFun: 1.0000e-006
                TolCon: 1.0000e-006
     InitialPopulation: []
         InitialScores: []
        InitialPenalty: 10
         PenaltyFactor: 100
          PlotInterval: 1
           CreationFcn: @gacreationuniform
     FitnessScalingFcn: @fitscalingrank
          SelectionFcn: @selectionstochunif
          CrossoverFcn: @crossoverscattered
           MutationFcn: {[1x1 function_handle]  [1]  [1]}
    DistanceMeasureFcn: []
             HybridFcn: []
               Display: 'final'
              PlotFcns: []
            OutputFcns: []
            Vectorized: 'off'
           UseParallel: 'never'

The function ga uses these default values if you do not pass in options as an input argument.

The value of each option is stored in a field of the options structure, such as options.PopulationSize. You can display any of these values by entering options. followed by the name of the field. For example, to display the size of the population for the genetic algorithm, enter

options.PopulationSize

ans =

    20

To create an options structure with a field value that is different from the default — for example to set PopulationSize to 100 instead of its default value 20 — enter

options = gaoptimset('PopulationSize', 100)

This creates the options structure with all values set to their defaults except for PopulationSize, which is set to 100.

If you now enter,

ga(@fitnessfun,nvars,[],[],[],[],[],[],[],options)

ga runs the genetic algorithm with a population size of 100.

If you subsequently decide to change another field in the options structure, such as setting PlotFcns to @gaplotbestf, which plots the best fitness function value at each generation, call gaoptimset with the syntax

options = gaoptimset(options, 'PlotFcns', @plotbestf)

This preserves the current values of all fields of options except for PlotFcns, which is changed to @plotbestf. Note that if you omit the input argument options, gaoptimset resets PopulationSize to its default value 20.

You can also set both PopulationSize and PlotFcns with the single command

options = gaoptimset('PopulationSize',100,'PlotFcns',@plotbestf)

Using Options and Problems from the Optimization Tool

As an alternative to creating an options structure using gaoptimset, you can set the values of options in the Optimization Tool and then export the options to a structure in the MATLAB® workspace, as described in the Importing and Exporting Your Work section of the Optimization Toolbox™ documentation. If you export the default options in the Optimization Tool, the resulting structure options has the same settings as the default structure returned by the command

options = gaoptimset(@ga)

except that the option 'Display' defaults to 'off' in an exported structure, and is 'final' in the default at the command line.

If you export a problem structure, ga_problem, from the Optimization Tool, you can apply ga to it using the syntax

[x fval] = ga(ga_problem)

The problem structure contains the following fields:

Reproducing Your Results

Because the genetic algorithm is stochastic—that is, it makes random choices—you get slightly different results each time you run the genetic algorithm. The algorithm uses the MATLAB uniform and normal random number generators, rand and randn, to makes random choices at each iteration. Each time ga calls rand and randn, their states are changed, so that the next time they are called, they return different random numbers. This is why the output of ga differs each time you run it.

If you need to reproduce your results exactly, you can call ga with an output argument that contains the current states of rand and randn and then reset the states to these values before running ga again. For example, to reproduce the output of ga applied to Rastrigin's function, call ga with the syntax

[x fval exitflag output] = ga(@rastriginsfcn, 2);

Suppose the results are

x =
    0.0027   -0.0052

fval =
    0.0068

The states of rand and randn are stored in the first two fields of output.

output = 
      randstate: [35x1 double]
     randnstate: [2x1 double]
    generations: 100
      funccount: 2000
        message: [1x64 char]

Then, reset the states, by entering

rand('twister', output.randstate);
randn('state', output.randnstate);

If you now run ga a second time, you get the same results.

You can reproduce your run in the Optimization Tool by checking the box Use random states from previous run in the Run solver and view results section.

Resuming ga from the Final Population of a Previous Run

By default, ga creates a new initial population each time you run it. However, you might get better results by using the final population from a previous run as the initial population for a new run. To do so, you must have saved the final population from the previous run by calling ga with the syntax

[x,fval,exitflag,output,final_pop] = ga(@fitnessfcn, nvars);

The last output argument is the final population. To run ga using final_pop as the initial population, enter

options = gaoptimset('InitialPop', final_pop);
[x,fval,exitflag,output,final_pop2] = ... 
		ga(@fitnessfcn,nvars,[],[],[],[],[],[],[],options);

You can then use final_pop2, the final population from the second run, as the initial population for a third run.

In Optimization Tool, you can choose to export a problem in a way that lets you resume the run. Simply check the box Include information needed to resume this run when exporting the problem.

This saves the final population, which becomes the initial population when imported.

If you want to run a problem that was saved with the final population, but would rather not use the initial population, simply delete or otherwise change the initial population in the Options > Population pane.

Running ga from an M-File

The command-line interface enables you to run the genetic algorithm many times, with different options settings, using an M-file. For example, you can run the genetic algorithm with different settings for Crossover fraction to see which one gives the best results. The following code runs the function ga 21 times, varying options.CrossoverFraction from 0 to 1 in increments of 0.05, and records the results.

options = gaoptimset('Generations',300);
rand('twister', 71); % These two commands are only included to
randn('state', 59); % make the results reproducible.
record=[];
for n=0:.05:1
	options = gaoptimset(options,'CrossoverFraction', n);
	[x fval]=ga(@rastriginsfcn, 10,[],[],[],[],[],[],[],options);
	record = [record; fval];
end

You can plot the values of fval against the crossover fraction with the following commands:

plot(0:.05:1, record);
xlabel('Crossover Fraction');
ylabel('fval')

The following plot appears.

The plot indicates that you get the best results by setting options.CrossoverFraction to a value somewhere between 0.6 and 0.95.

You can get a smoother plot of fval as a function of the crossover fraction by running ga 20 times and averaging the values of fval for each crossover fraction. The following figure shows the resulting plot.

The plot narrows the range of best choices for options.CrossoverFraction to values between 0.7 and 0.9.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS