CMA-ES 和python
来源:互联网 发布:约会软件哪个好 编辑:程序博客网 时间:2024/05/16 17:45
https://www.lri.fr/~hansen/pythoncma.html点击打开链接
cma (version 0.91.00 $Revision: 3103 $)index
cma.py
Module cma implements the CMA-ES, Covariance Matrix Adaptation Evolution
Strategy, a stochastic optimizer for robust non-linear non-convex
derivative-free function minimization for Python versions 2.6 and 2.7
(in Python 2.5 the collections import does not provide the class MutableMapping).
CMA-ES searches for a minimizer (a solution x in R**n) of an
objective function f (cost function), such that f(x) is
minimal. Regarding f, only function values for candidate solutions
need to be available, gradients are not necessary. Even less
restrictive, only a passably reliable ranking of the candidate
solutions in each iteration is necessary, the function values
itself do not matter. Some termination criteria however depend
on actual f-values.
Two interfaces are provided:
- function `fmin(func, x0, sigma0,...)`
runs a complete minimization
of the objective function func with CMA-ES.
- class `CMAEvolutionStrategy`
allows for minimization such that the
control of the iteration loop remains with the user.
Used packages:
- unavoidable: `numpy` (see `barecmaes2.py` if `numpy` is not
available),
- avoidable with small changes: `time`, `sys`
- optional: `matplotlib.pylab` (for `plot` etc., highly
recommended), `pprint` (pretty print), `pickle` (in class
`Sections`), `doctest`, `inspect`, `pygsl` (never by default)
Testing
-------
The code can be tested on a given system. Typing::
python cma.py --test --quiet
or in the Python shell ``ipython -pylab``::
run cma.py --test --quiet
runs ``doctest.testmod(cma)`` showing only exceptions (and not the
tests that fail due to small differences in the output) and should
run without complaints in about under two minutes. On some systems,
the pop up windows must be closed manually to continue and finish
the test.
Example
-------
::
import cma
help(cma) # "this" help message, use cma? in ipython
help(cma.fmin)
help(cma.CMAEvolutionStrategy)
help(cma.Options)
cma.Options('tol') # display 'tolerance' termination options
cma.Options('verb') # display verbosity options
res = cma.fmin(cma.Fcts.tablet, 15 * [1], 1)
res[0] # best evaluated solution
res[5] # mean solution, presumably better with noise
:See: `fmin()`, `Options`, `CMAEvolutionStrategy`
:Author: Nikolaus Hansen, 2008-2012
:License: GPL 2 and 3
Modules collections
numpymatplotlib.pylab
systime
Classes
- __builtin__.dict(__builtin__.object)
- CMAStopDict
- Options
- SolutionDictOld
- __builtin__.object
- AII
- BaseDataLogger
- CMADataLogger
- BestSolution
- BlancClass
- BoundPenalty
- CMAParameters
- ElapsedTime
- FitnessFunctions
- GenoPheno
- GenoPhenoBase
- MathHelperFunctions
- Misc
- NoiseHandler
- OOOptimizer
- CMAEvolutionStrategy
- Rotation
- Sections
- TimeIt
- _abcoll.MutableMapping(_abcoll.Mapping)
- DerivedDictBase
- SolutionDict
class AII(__builtin__.object) unstable experimental code, updates ps, sigma, sigmai, pr, r, sigma_r, mean,
all from self.
Depends on that the ordering of solutions has not change upon calling update
should become a OOOptimizer in far future?
Methods defined here:
- __init__(self, x0, sigma0, randn=<built-in method randn of mtrand.RandomState object>)
- TODO: check scaling of r-learing: seems worse than linear: 9e3 25e3 65e3 (10,20,40-D)
- ask(self, popsize)
- initialize(self)
- alias ``reset``, set all state variables to initial values
- tell(self, X, f)
- update
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class BaseDataLogger(__builtin__.object) "abstract" base class for a data logger that can be used with an `OOOptimizer`
Methods defined here:
- add(self, optim=None, more_data=[])
- abstract method, add a "data point" from the state of `optim` into the
logger, the argument `optim` can be omitted if it was `register()`-ed before,
acts like an event handler
- data(self)
- return logged data in a dictionary (not implemented)
- disp(self)
- display some data trace (not implemented)
- plot(self)
- plot data (not implemented)
- register(self, optim)
- abstract method, register an optimizer `optim`, only needed if `add()` is
called without a value for the `optim` argument
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class BestSolution(__builtin__.object) container to keep track of the best solution seen
Methods defined here:
- __init__(self, x=None, f=inf, evals=None)
- initialize the best solution with `x`, `f`, and `evals`.
Better solutions have smaller `f`-values.
- get(self)
- return ``(x, f, evals)``
- update(self, arx, xarchive=None, arf=None, evals=None)
- checks for better solutions in list `arx`, based on the smallest
corresponding value in `arf`, alternatively, `update` may be called
with a `BestSolution` instance like ``update(another_best_solution)``
in which case the better solution becomes the current best.
`xarchive` is used to retrieve the genotype of a solution.
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class BlancClass(__builtin__.object) blanc container class for having a collection of attributes
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class BoundPenalty(__builtin__.object) Computes the boundary penalty. Must be updated each iteration,
using the `update` method.
Details
-------
The penalty computes like ``sum(w[i] * (x[i]-xfeas[i])**2)``,
where `xfeas` is the closest feasible (in-bounds) solution from `x`.
The weight `w[i]` should be updated during each iteration using
the update method.
This class uses `GenoPheno.into_bounds` in method `update` to access
domain boundary values and repair. This inconsistency might be
removed in future.
Methods defined here:
- __call__(self, x, archive, gp)
- returns the boundary violation penalty for `x` ,where `x` is a
single solution or a list or array of solutions.
If `bounds` is not `None`, the values in `bounds` are used, see `__init__`
- __init__(self, bounds=None)
- Argument bounds can be `None` or ``bounds[0]`` and ``bounds[1]``
are lower and upper domain boundaries, each is either `None` or
a scalar or a list or array of appropriate size.
- feasible_ratio(self, solutions)
- counts for each coordinate the number of feasible values in
``solutions`` and returns an array of length ``len(solutions[0])``
with the ratios.
`solutions` is a list or array of repaired `Solution` instances
- has_bounds(self)
- return True, if any variable is bounded
- repair(self, x, bounds=None, copy=False, copy_always=False)
- sets out-of-bounds components of ``x`` on the bounds.
Arguments
---------
`bounds`
can be `None`, in which case the "default" bounds are used,
or ``[lb, ub]``, where `lb` and `ub`
represent lower and upper domain bounds respectively that
can be `None` or a scalar or a list or array of length ``len(self)``
code is more or less copy-paste from Solution.repair, but never tested
- update(self, function_values, es, bounds=None)
- updates the weights for computing a boundary penalty.
Arguments
---------
`function_values`
all function values of recent population of solutions
`es`
`CMAEvolutionStrategy` object instance, in particular the
method `into_bounds` of the attribute `gp` of type `GenoPheno`
is used.
`bounds`
not (yet) in use other than for ``bounds == [None, None]`` nothing
is updated.
Reference: Hansen et al 2009, A Method for Handling Uncertainty...
IEEE TEC, with addendum at http://www.lri.fr/~hansen/TEC2009online.pdf
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class CMADataLogger(BaseDataLogger) data logger for class `CMAEvolutionStrategy`. The logger is
identified by its name prefix and writes or reads according
data files.
Examples
========
::
import cma
es = cma.CMAEvolutionStrategy(...)
data = cma.CMADataLogger().register(es)
while not es.stop():
...
data.add() # add can also take an argument
data.plot() # or a short cut can be used:
cma.plot() # plot data from logger with default name
data2 = cma.CMADataLogger(another_filename_prefix).load()
data2.plot()
data2.disp()
::
import cma
from pylab import *
res = cma.fmin(cma.Fcts.sphere, rand(10), 1e-0)
dat = res[-1] # the CMADataLogger
dat.load() # by "default" data are on disk
semilogy(dat.f[:,0], dat.f[:,5]) # plot f versus iteration, see file header
show()
Details
=======
After loading data, the logger has the attributes `xmean`, `xrecent`, `std`, `f`, and `D`,
corresponding to xmean, xrecentbest, stddev, fit, and axlen filename trails.
:See: `disp()`, `plot()`
- Method resolution order:
- CMADataLogger
- BaseDataLogger
- __builtin__.object
Methods defined here:
- __init__(self, name_prefix='outcmaes', modulo=1, append=False)
- initialize logging of data from a `CMAEvolutionStrategy` instance,
default modulo expands to 1 == log with each call
- add(self, es=None, more_data=[], modulo=None)
- append some logging data from `CMAEvolutionStrategy` class instance `es`,
if ``number_of_times_called % modulo`` equals to zero, never if ``modulo==0``.
The sequence ``more_data`` must always have the same length.
- closefig(self)
- disp(self, idx=100)
- displays selected data from (files written by) the class `CMADataLogger`.
Arguments
---------
`idx`
indices corresponding to rows in the data file;
if idx is a scalar (int), the first two, then every idx-th,
and the last three rows are displayed. Too large index values are removed.
Example
-------
>>> import cma, numpy as np
>>> res = cma.fmin(cma.fcts.elli, 7 * [0.1], 1, verb_disp=1e9) # generate data
>>> assert res[1] < 1e-9
>>> assert res[2] < 4400
>>> l = cma.CMADataLogger() # == res[-1], logger with default name, "points to" above data
>>> l.disp([0,-1]) # first and last
>>> l.disp(20) # some first/last and every 20-th line
>>> l.disp(np.r_[0:999999:100, -1]) # every 100-th and last
>>> l.disp(np.r_[0, -10:0]) # first and ten last
>>> cma.disp(l.name_prefix, np.r_[0::100, -10:]) # the same as l.disp(...)
Details
-------
The data line with the best f-value is displayed as last line.
:See: `disp()`
- downsampling(self, factor=10, first=3, switch=True)
- rude downsampling of a `CMADataLogger` data file by `factor`, keeping
also the first `first` entries. This function is a stump and subject
to future changes.
Arguments
---------
- `factor` -- downsampling factor
- `first` -- keep first `first` entries
- `switch` -- switch the new logger name to oldname+'down'
Details
-------
``self.name_prefix+'down'`` files are written
Example
-------
::
import cma
cma.downsampling() # takes outcmaes* files
cma.plot('outcmaesdown')
- initialize(self, modulo=None)
- reset logger, overwrite original files, `modulo`: log only every modulo call
- load(self, filenameprefix=None)
- loads data from files written and return a data dictionary, *not*
a prerequisite for using `plot()` or `disp()`.
Argument `filenameprefix` is the filename prefix of data to be loaded (five files),
by default ``'outcmaes'``.
Return data dictionary with keys `xrecent`, `xmean`, `f`, `D`, `std`
- plot(self, fig=None, iabscissa=1, iteridx=None, plot_mean=True, foffset=1e-19, x_opt=None, fontsize=10)
- plot data from a `CMADataLogger` (using the files written by the logger).
Arguments
---------
`fig`
figure number, by default 325
`iabscissa`
``0==plot`` versus iteration count,
``1==plot`` versus function evaluation number
`iteridx`
iteration indices to plot
Return `CMADataLogger` itself.
Examples
--------
::
import cma
logger = cma.CMADataLogger() # with default name
# try to plot the "default logging" data (e.g. from previous fmin calls)
logger.plot() # to continue you might need to close the pop-up window
# once and call plot() again.
# This behavior seems to disappear in subsequent
# calls of plot(). Also using ipython with -pylab
# option might help.
cma.savefig('fig325.png') # save current figure
logger.closefig()
Dependencies: matlabplotlib/pylab.
- register(self, es, append=None, modulo=None)
- register a `CMAEvolutionStrategy` instance for logging,
``append=True`` appends to previous data logged under the same name,
by default previous data are overwritten.
- save(self, nameprefix, switch=False)
- saves logger data to a different set of files, for
``switch=True`` also the loggers name prefix is switched to
the new value
Static methods defined here:
- plotdivers(dat, iabscissa, foffset)
- helper function for `plot()` that plots all what is
in the upper left subplot like fitness, sigma, etc.
Arguments
---------
`iabscissa` in ``(0,1)``
0==versus fevals, 1==versus iteration
`foffset`
offset to fitness for log-plot
:See: `plot()`
Data and other attributes defined here:
- default_prefix = 'outcmaes'
- names = ('axlen', 'fit', 'stddev', 'xmean', 'xrecentbest')
Methods inherited from BaseDataLogger:
- data(self)
- return logged data in a dictionary (not implemented)
Data descriptors inherited from BaseDataLogger:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class CMAEvolutionStrategy(OOOptimizer) CMA-ES stochastic optimizer class with ask-and-tell interface.
See `fmin` for the one-line-call functional interface.
Calling sequence
================
``optim = CMAEvolutionStrategy(x0, sigma0, opts)``
returns a class instance.
Arguments
---------
`x0`
initial solution, starting point.
`sigma0`
initial standard deviation. The problem
variables should have been scaled, such that a single
standard deviation on all variables is useful and the
optimum is expected to lie within about `x0` +- ``3*sigma0``.
See also options `scaling_of_variables`.
Often one wants to check for solutions close to the initial
point. This allows for an easier check for consistency of
the objective function and its interfacing with the optimizer.
In this case, a much smaller `sigma0` is advisable.
`opts`
options, a dictionary with optional settings,
see class `Options`.
Main interface / usage
======================
The ask-and-tell interface is inherited from the generic `OOOptimizer`
interface for iterative optimization algorithms (see there). With ::
optim = CMAEvolutionStrategy(8 * [0.5], 0.2)
an object instance is generated. In each iteration ::
solutions = optim.ask()
is used to ask for new candidate solutions (possibly several times) and ::
optim.tell(solutions, func_values)
passes the respective function values to `optim`. Instead of `ask()`,
the class `CMAEvolutionStrategy` also provides ::
(solutions, func_values) = optim.ask_and_eval(objective_func)
Therefore, after initialization, an entire optimization can be written
in two lines like ::
while not optim.stop():
optim.tell(*optim.ask_and_eval(objective_func))
Without the freedom of executing additional lines within the iteration,
the same reads in a single line as ::
optim.optimize(objective_func)
Besides for termination criteria, in CMA-ES only
the ranks of the `func_values` are relevant.
Attributes and Properties
=========================
- `inputargs` -- passed input arguments
- `inopts` -- passed options
- `opts` -- actually used options, some of them can be changed any
time, see class `Options`
- `popsize` -- population size lambda, number of candidate solutions
returned by `ask()`
Details
=======
The following two enhancements are turned off by default.
**Active CMA** is implemented with option ``CMA_active`` and conducts
an update of the covariance matrix with negative weights. The
exponential update is implemented, where from a mathematical
viewpoint positive definiteness is guarantied. The update is applied
after the default update and only before the covariance matrix is
decomposed, which limits the additional computational burden to be
at most a factor of three (typically smaller). A typical speed up
factor (number of f-evaluations) is between 1.1 and two.
References: Jastrebski and Arnold, CEC 2006, Glasmachers et al, GECCO 2010.
**Selective mirroring** is implemented with option ``CMA_mirrors`` in
the method ``get_mirror()``. Only the method `ask_and_eval()` will
then sample selectively mirrored vectors. In selective mirroring, only
the worst solutions are mirrored. With the default small number of mirrors,
*pairwise selection* (where at most one of the two mirrors contribute to the
update of the distribution mean) is implicitely guarantied under selective
mirroring and therefore not explicitly implemented.
References: Brockhoff et al, PPSN 2010, Auger et al, GECCO 2011.
Examples
========
Super-short example, with output shown:
>>> import cma
>>> # construct an object instance in 4-D, sigma0=1
>>> es = cma.CMAEvolutionStrategy(4 * [1], 1, {'seed':234})
(4_w,8)-CMA-ES (mu_w=2.6,w_1=52%) in dimension 4 (seed=234)
>>>
>>> # iterate until termination
>>> while not es.stop():
... X = es.ask()
... es.tell(X, [cma.fcts.elli(x) for x in X])
... es.disp() # by default sparse, see option verb_disp
Iterat #Fevals function value axis ratio sigma minstd maxstd min:sec
1 8 2.093015112685775e+04 1.0e+00 9.27e-01 9e-01 9e-01 0:0.0
2 16 4.964814235917688e+04 1.1e+00 9.54e-01 9e-01 1e+00 0:0.0
3 24 2.876682459926845e+05 1.2e+00 1.02e+00 9e-01 1e+00 0:0.0
100 800 6.809045875281943e-01 1.3e+02 1.41e-02 1e-04 1e-02 0:0.2
200 1600 2.473662150861846e-10 8.0e+02 3.08e-05 1e-08 8e-06 0:0.5
233 1864 2.766344961865341e-14 8.6e+02 7.99e-07 8e-11 7e-08 0:0.6
>>>
>>> cma.pprint(es.result())
(Solution([ -1.98546755e-09, -1.10214235e-09, 6.43822409e-11,
-1.68621326e-11]),
4.5119610261406537e-16,
1666,
1672,
209,
array([ -9.13545269e-09, -1.45520541e-09, -6.47755631e-11,
-1.00643523e-11]),
array([ 3.20258681e-08, 3.15614974e-09, 2.75282215e-10,
3.27482983e-11]))
>>>
>>> # help(es.result) shows
result(self) method of cma.CMAEvolutionStrategy instance
return ``(xbest, f(xbest), evaluations_xbest, evaluations, iterations, pheno(xmean), effective_stds)``
Using the multiprocessing module, we can evaluate the function in parallel with a simple
modification of the example ::
import multiprocessing
# prepare es = ...
pool = multiprocessing.Pool(es.popsize)
while not es.stop():
X = es.ask()
es.tell(X, pool.map_async(cma.fcts.elli, X))
Example with a data logger, lower bounds (at zero) and handling infeasible solutions:
>>> import cma
>>> import numpy as np
>>> es = cma.CMAEvolutionStrategy(10 * [0.2], 0.5, {'bounds': [0, np.inf]})
>>> logger = cma.CMADataLogger().register(es)
>>> while not es.stop():
... fit, X = [], []
... while len(X) < es.popsize:
... curr_fit = np.NaN
... while curr_fit is np.NaN:
... x = es.ask(1)[0]
... curr_fit = cma.fcts.somenan(x, cma.fcts.elli) # might return np.NaN
... X.append(x)
... fit.append(curr_fit)
... es.tell(X, fit)
... logger.add()
... es.disp()
<output omitted>
>>>
>>> assert es.result()[1] < 1e-9
>>> assert es.result()[2] < 9000 # by internal termination
>>> logger.plot() # plot data
>>> cma.show()
>>> print(' *** if execution stalls close the figure window to continue (and check out ipython --pylab) ***')
Example implementing restarts with increasing popsize (IPOP), output is not displayed:
>>> import cma, numpy as np
>>>
>>> # restart with increasing population size (IPOP)
>>> bestever = cma.BestSolution()
>>> for lam in 10 * 2**np.arange(7): # 10, 20, 40, 80, ..., 10 * 2**6
... es = cma.CMAEvolutionStrategy('6 - 8 * np.random.rand(9)', # 9-D
... 5, # initial std sigma0
... {'popsize': lam,
... 'verb_append': bestever.evalsall}) # pass options
... logger = cma.CMADataLogger().register(es, append=bestever.evalsall)
... while not es.stop():
... X = es.ask() # get list of new solutions
... fit = [cma.fcts.rastrigin(x) for x in X] # evaluate each solution
... es.tell(X, fit) # besides for termination only the ranking in fit is used
...
... # display some output
... logger.add() # add a "data point" to the log, writing in files
... es.disp() # uses option verb_disp with default 100
...
... print('termination:', es.stop())
... cma.pprint(es.best.__dict__)
...
... bestever.update(es.best)
...
... # show a plot
... logger.plot();
... if bestever.f < 1e-8: # global optimum was hit
... break
<output omitted>
>>> assert es.result()[1] < 1e-8
On the Rastrigin function, usually after five restarts the global optimum
is located.
The final example shows how to resume:
>>> import cma, pickle
>>>
>>> es = cma.CMAEvolutionStrategy(12 * [0.1], # a new instance, 12-D
... 0.5) # initial std sigma0
>>> logger = cma.CMADataLogger().register(es)
>>> es.optimize(cma.fcts.rosen, logger, iterations=100)
>>> logger.plot()
>>> pickle.dump(es, open('saved-cma-object.pkl', 'w'))
>>> print('saved')
>>> del es, logger # let's start fresh
>>>
>>> es = pickle.load(open('saved-cma-object.pkl'))
>>> print('resumed')
>>> logger = cma.CMADataLogger(es.opts['verb_filenameprefix'] # use same name
... ).register(es, True) # True: append to old log data
>>> es.optimize(cma.fcts.rosen, logger, verb_disp=200)
>>> assert es.result()[2] < 15000
>>> cma.pprint(es.result())
>>> logger.plot()
Missing Features
================
Option ``randn`` to pass a random number generator.
:See: `fmin()`, `Options`, `plot()`, `ask()`, `tell()`, `ask_and_eval()`
- Method resolution order:
- CMAEvolutionStrategy
- OOOptimizer
- __builtin__.object
Methods defined here:
- __init__(self, x0, sigma0, inopts={})
- see class `CMAEvolutionStrategy`
- ask(self, number=None, xmean=None, sigma_fac=1)
- get new candidate solutions, sampled from a multi-variate
normal distribution and transformed to f-representation
(phenotype) to be evaluated.
Arguments
---------
`number`
number of returned solutions, by default the
population size ``popsize`` (AKA ``lambda``).
`xmean`
distribution mean
`sigma`
multiplier for internal sample width (standard
deviation)
Return
------
A list of N-dimensional candidate solutions to be evaluated
Example
-------
>>> import cma
>>> es = cma.CMAEvolutionStrategy([0,0,0,0], 0.3)
>>> while not es.stop() and es.best.f > 1e-6: # my_desired_target_f_value
... X = es.ask() # get list of new solutions
... fit = [cma.fcts.rosen(x) for x in X] # call function rosen with each solution
... es.tell(X, fit) # feed values
:See: `ask_and_eval`, `ask_geno`, `tell`
- ask_and_eval(self, func, args=(), number=None, xmean=None, sigma_fac=1, evaluations=1, aggregation=<function median>)
- samples `number` solutions and evaluates them on `func`, where
each solution `s` is resampled until ``func(s) not in (numpy.NaN, None)``.
Arguments
---------
`func`
objective function
`args`
additional parameters for `func`
`number`
number of solutions to be sampled, by default
population size ``popsize`` (AKA lambda)
`xmean`
mean for sampling the solutions, by default ``self.mean``.
`sigma_fac`
multiplier for sampling width, standard deviation, for example
to get a small perturbation of solution `xmean`
`evaluations`
number of evaluations for each sampled solution
`aggregation`
function that aggregates `evaluations` values to
as single value.
Return
------
``(X, fit)``, where
X -- list of solutions
fit -- list of respective function values
Details
-------
When ``func(x)`` returns `NaN` or `None` a new solution is sampled until
``func(x) not in (numpy.NaN, None)``. The argument to `func` can be
freely modified within `func`.
Depending on the ``CMA_mirrors`` option, some solutions are not sampled
independently but as mirrors of other bad solutions. This is a simple
derandomization that can save 10-30% of the evaluations in particular
with small populations, for example on the cigar function.
Example
-------
>>> import cma
>>> x0, sigma0 = 8*[10], 1 # 8-D
>>> es = cma.CMAEvolutionStrategy(x0, sigma0)
>>> while not es.stop():
... X, fit = es.ask_and_eval(cma.fcts.elli) # handles NaN with resampling
... es.tell(X, fit) # pass on fitness values
... es.disp(20) # print every 20-th iteration
>>> print('terminated on ' + str(es.stop()))
<output omitted>
A single iteration step can be expressed in one line, such that
an entire optimization after initialization becomes
::
while not es.stop():
es.tell(*es.ask_and_eval(cma.fcts.elli))
- ask_geno(self, number=None, xmean=None, sigma_fac=1)
- get new candidate solutions in genotyp, sampled from a
multi-variate normal distribution.
Arguments are
`number`
number of returned solutions, by default the
population size `popsize` (AKA lambda).
`xmean`
distribution mean
`sigma_fac`
multiplier for internal sample width (standard
deviation)
`ask_geno` returns a list of N-dimensional candidate solutions
in genotyp representation and is called by `ask`.
:See: `ask`, `ask_and_eval`
- clip_or_fit_solutions(self, pop, idx)
- make sure that solutions fit to sample distribution, this interface will probably change.
In particular the frequency of long vectors appearing in pop[idx] - self.mean is limited.
- disp(self, modulo=None)
- prints some infos according to `disp_annotation()`, if
``iteration_counter % modulo == 0``
- disp_annotation(self)
- print annotation for `disp()`
- feedForResume(self, X, function_values)
- Given all "previous" candidate solutions and their respective
function values, the state of a `CMAEvolutionStrategy` object
can be reconstructed from this history. This is the purpose of
function `feedForResume`.
Arguments
---------
`X`
(all) solution points in chronological order, phenotypic
representation. The number of points must be a multiple
of popsize.
`function_values`
respective objective function values
Details
-------
`feedForResume` can be called repeatedly with only parts of
the history. The part must have the length of a multiple
of the population size.
`feedForResume` feeds the history in popsize-chunks into `tell`.
The state of the random number generator might not be
reconstructed, but this would be only relevant for the future.
Example
-------
::
import cma
# prepare
(x0, sigma0) = ... # initial values from previous trial
X = ... # list of generated solutions from a previous trial
f = ... # respective list of f-values
# resume
es = cma.CMAEvolutionStrategy(x0, sigma0)
es.feedForResume(X, f)
# continue with func as objective function
while not es.stop():
X = es.ask()
es.tell(X, [func(x) for x in X])
Credits to Dirk Bueche and Fabrice Marchal for the feeding idea.
:See: class `CMAEvolutionStrategy` for a simple dump/load to resume
- get_mirror(self, x)
- return ``pheno(self.mean - (geno(x) - self.mean))``.
TODO: this implementation is yet experimental.
Selectively mirrored sampling improves to a moderate extend but
overadditively with active CMA for quite understandable reasons.
Optimal number of mirrors are suprisingly small: 1,2,3 for maxlam=7,13,20
however note that 3,6,10 are the respective maximal possible mirrors that
must be clearly suboptimal.
- mahalanobisNorm(self, dx)
- compute the Mahalanobis norm that is induced by the adapted covariance
matrix C times sigma**2.
Argument
--------
A *genotype* difference `dx`.
Example
-------
>>> import cma, numpy
>>> es = cma.CMAEvolutionStrategy(numpy.ones(10), 1)
>>> xx = numpy.random.randn(2, 10)
>>> d = es.mahalanobisNorm(es.gp.geno(xx[0]-xx[1]))
`d` is the distance "in" the true sample distribution,
sampled points have a typical distance of ``sqrt(2*es.N)``,
where `N` is the dimension. In the example, `d` is the
Euclidean distance, because C = I and sigma = 1.
- mirror_idx_cov(self, f_values, idx1)
- obsolete and subject to removal (TODO),
return indices for negative ("active") update of the covariance matrix
assuming that ``f_values[idx1[i]]`` and ``f_values[-1-i]`` are
the corresponding mirrored values
computes the index of the worse solution sorted by the f-value of the
better solution.
TODO: when the actual mirror was rejected, it is better
to return idx1 instead of idx2.
Remark: this function might not be necessary at all: if the worst solution
is the best mirrored, the covariance matrix updates cancel (cave: weights
and learning rates), which seems what is desirable. If the mirror is bad,
as strong negative update is made, again what is desirable.
And the fitness--step-length correlation is in part addressed by
using flat weights.
- mirror_penalized(self, f_values, idx)
- obsolete and subject to removal (TODO),
return modified f-values such that for each mirror one becomes worst.
This function is useless when selective mirroring is applied with no
more than (lambda-mu)/2 solutions.
Mirrors are leading and trailing values in ``f_values``.
- readProperties(self)
- reads dynamic parameters from property file (not implemented)
- repair_genotype(self, x)
- make sure that solutions fit to sample distribution, this interface will probably change.
In particular the frequency of x - self.mean being long is limited.
- result(self)
- return ``(xbest, f(xbest), evaluations_xbest, evaluations, iterations, pheno(xmean), effective_stds)``
- stop(self, check=True)
- return a dictionary with the termination status.
With ``check==False``, the termination conditions are not checked and
the status might not reflect the current situation.
- tell(self, solutions, function_values, function_values_reevaluated=None, check_points=None, copy=False)
- pass objective function values to prepare for next
iteration. This core procedure of the CMA-ES algorithm updates
all state variables: two evolution paths, the distribution mean,
the covariance matrix and a step-size.
Arguments
---------
`solutions`
list or array of candidate solution points (of
type `numpy.ndarray`), most presumably before
delivered by method `ask()` or `ask_and_eval()`.
`function_values`
list or array of objective function values
corresponding to the respective points. Beside for termination
decisions, only the ranking of values in `function_values`
is used.
`check_points`
if ``True``, allows to savely pass solutions that are
not necessarily generated using `ask()`. Might just as well be a
list of indices to be checked in solutions. Value ``None`` defaults
to ``False``.
`copy`
``solutions`` might be modified, if ``copy is False``
Details
-------
`tell()` updates the parameters of the multivariate
normal search distribution, namely covariance matrix and
step-size and updates also the attributes `countiter` and
`countevals`. To check the points for consistency is quadratic
in the dimension (like sampling points).
Bugs
----
The effect of changing the solutions delivered by `ask()` depends on whether
boundary handling is applied. With boundary handling, modifications are
disregarded. This is necessary to apply the default boundary handling that
uses unrepaired solutions but might change in future.
Example
-------
::
import cma
func = cma.fcts.elli # choose objective function
es = cma.CMAEvolutionStrategy(cma.np.random.rand(10), 1)
while not es.stop():
X = es.ask()
es.tell(X, [func(x) for x in X])
es.result() # where the result can be found
:See: class `CMAEvolutionStrategy`, `ask()`, `ask_and_eval()`, `fmin()`
- updateBD(self)
- update internal variables for sampling the distribution with the
current covariance matrix C. This method is O(N^3), if C is not diagonal.
- update_exponential(self, Z, eta, BDpair=None)
- exponential update of C that guarantees positive definiteness, that is,
instead of the assignment ``C = C + eta * Z``,
C gets C**.5 * exp(eta * C**-.5 * Z * C**-.5) * C**.5.
Parameter Z should have expectation zero, e.g. sum(w[i] * z[i] * z[i].T) - C
if E z z.T = C.
This function conducts two eigendecompositions, assuming that
B and D are not up to date, unless `BDpair` is given. Given BDpair,
B is the eigensystem and D is the vector of sqrt(eigenvalues), one
eigendecomposition is omitted.
Reference: Glasmachers et al 2010, Exponential Natural Evolution Strategies
Data descriptors defined here:
- popsize
- number of samples by default returned by` ask()`
Methods inherited from OOOptimizer:
- initialize(self)
- (re-)set to the initial state
- optimize(self, objectivefct, logger=None, verb_disp=20, iterations=None)
- find minimizer of `objectivefct` by iterating over `OOOptimizer` `self`
with verbosity `verb_disp`, using `BaseDataLogger` `logger` with at
most `iterations` iterations. ::
return result() + (stop(), self, logger)
Example
-------
>>> import cma
>>> res = cma.CMAEvolutionStrategy(7 * [0.1], 0.5).optimize(cma.fcts.rosen, None, 100)
(4_w,9)-CMA-ES (mu_w=2.8,w_1=49%) in dimension 7 (seed=630721393)
Iterat #Fevals function value axis ratio sigma minstd maxstd min:sec
1 9 3.163954777181882e+01 1.0e+00 4.12e-01 4e-01 4e-01 0:0.0
2 18 3.299006223906629e+01 1.0e+00 3.60e-01 3e-01 4e-01 0:0.0
3 27 1.389129389866704e+01 1.1e+00 3.18e-01 3e-01 3e-01 0:0.0
100 900 2.494847340045985e+00 8.6e+00 5.03e-02 2e-02 5e-02 0:0.3
200 1800 3.428234862999135e-01 1.7e+01 3.77e-02 6e-03 3e-02 0:0.5
300 2700 3.216640032470860e-04 5.6e+01 6.62e-03 4e-04 9e-03 0:0.8
400 3600 6.155215286199821e-12 6.6e+01 7.44e-06 1e-07 4e-06 0:1.1
438 3942 1.187372505161762e-14 6.0e+01 3.27e-07 4e-09 9e-08 0:1.2
438 3942 1.187372505161762e-14 6.0e+01 3.27e-07 4e-09 9e-08 0:1.2
('termination by', {'tolfun': 1e-11})
('best f-value =', 1.1189867885201275e-14)
('solution =', array([ 1. , 1. , 1. , 0.99999999, 0.99999998,
0.99999996, 0.99999992]))
>>> print(res[0])
[ 1. 1. 1. 0.99999999 0.99999998 0.99999996
0.99999992]
Static methods inherited from OOOptimizer:
- abstract()
- marks a method as abstract, ie to be implemented by a subclass
Data descriptors inherited from OOOptimizer:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class CMAParameters(__builtin__.object) strategy parameters like population size and learning rates.
Note:
contrary to `Options`, `CMAParameters` is not (yet) part of the
"user-interface" and subject to future changes (it might become
a `collections.namedtuple`)
Example
-------
>>> import cma
>>> es = cma.CMAEvolutionStrategy(20 * [0.1], 1)
(6_w,12)-CMA-ES (mu_w=3.7,w_1=40%) in dimension 20 (seed=504519190) # the seed is "random" by default
>>>
>>> type(es.sp) # sp contains the strategy parameters
<class 'cma.CMAParameters'>
>>>
>>> es.sp.disp()
{'CMA_on': True,
'N': 20,
'c1': 0.004181139918745593,
'c1_sep': 0.034327992810300939,
'cc': 0.17176721127681213,
'cc_sep': 0.25259494835857677,
'cmean': 1.0,
'cmu': 0.0085149624979034746,
'cmu_sep': 0.057796356229390715,
'cs': 0.21434997799189287,
'damps': 1.2143499779918929,
'mu': 6,
'mu_f': 6.0,
'mueff': 3.7294589343030671,
'popsize': 12,
'rankmualpha': 0.3,
'weights': array([ 0.40240294, 0.25338908, 0.16622156, 0.10437523, 0.05640348,
0.01720771])}
>>>
>> es.sp == cma.CMAParameters(20, 12, cma.Options().evalall({'N': 20}))
True
:See: `Options`, `CMAEvolutionStrategy`
Methods defined here:
- __init__(self, N, opts, ccovfac=1, verbose=True)
- Compute strategy parameters, mainly depending on
dimension and population size, by calling `set`
- disp(self)
- set(self, opts, popsize=None, ccovfac=1, verbose=True)
- Compute strategy parameters as a function
of dimension and population size
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class CMAStopDict(__builtin__.dict) keep and update a termination condition dictionary, which is
"usually" empty and returned by `CMAEvolutionStrategy.stop()`.
Details
-------
This could be a nested class, but nested classes cannot be serialized.
:See: `stop()`
- Method resolution order:
- CMAStopDict
- __builtin__.dict
- __builtin__.object
Methods defined here:
- __call__(self, es)
- update the dictionary
- __init__(self, d={})
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Methods inherited from __builtin__.dict:
- __cmp__(...)
- x.__cmp__(y) <==> cmp(x,y)
- __contains__(...)
- D.__contains__(k) -> True if D has a key k, else False
- __delitem__(...)
- x.__delitem__(y) <==> del x[y]
- __eq__(...)
- x.__eq__(y) <==> x==y
- __ge__(...)
- x.__ge__(y) <==> x>=y
- __getattribute__(...)
- x.__getattribute__('name') <==> x.name
- __getitem__(...)
- x.__getitem__(y) <==> x[y]
- __gt__(...)
- x.__gt__(y) <==> x>y
- __iter__(...)
- x.__iter__() <==> iter(x)
- __le__(...)
- x.__le__(y) <==> x<=y
- __len__(...)
- x.__len__() <==> len(x)
- __lt__(...)
- x.__lt__(y) <==> x<y
- __ne__(...)
- x.__ne__(y) <==> x!=y
- __repr__(...)
- x.__repr__() <==> repr(x)
- __setitem__(...)
- x.__setitem__(i, y) <==> x[i]=y
- __sizeof__(...)
- D.__sizeof__() -> size of D in memory, in bytes
- clear(...)
- D.clear() -> None. Remove all items from D.
- copy(...)
- D.copy() -> a shallow copy of D
- get(...)
- D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
- has_key(...)
- D.has_key(k) -> True if D has a key k, else False
- items(...)
- D.items() -> list of D's (key, value) pairs, as 2-tuples
- iteritems(...)
- D.iteritems() -> an iterator over the (key, value) items of D
- iterkeys(...)
- D.iterkeys() -> an iterator over the keys of D
- itervalues(...)
- D.itervalues() -> an iterator over the values of D
- keys(...)
- D.keys() -> list of D's keys
- pop(...)
- D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
- popitem(...)
- D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
- setdefault(...)
- D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
- update(...)
- D.update(E, **F) -> None. Update D from dict/iterable E and F.
If E has a .keys() method, does: for k in E: D[k] = E[k]
If E lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
- values(...)
- D.values() -> list of D's values
- viewitems(...)
- D.viewitems() -> a set-like object providing a view on D's items
- viewkeys(...)
- D.viewkeys() -> a set-like object providing a view on D's keys
- viewvalues(...)
- D.viewvalues() -> an object providing a view on D's values
Data and other attributes inherited from __builtin__.dict:
- __hash__ = None
- __new__ = <built-in method __new__ of type object>
- T.__new__(S, ...) -> a new object with type S, a subtype of T
- fromkeys = <built-in method fromkeys of type object>
- dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
class DerivedDictBase(_abcoll.MutableMapping) for conveniently adding features to a dictionary. The actual
dictionary is in ``self.data``. Copy-paste
and modify setitem, getitem, and delitem, if necessary
- Method resolution order:
- DerivedDictBase
- _abcoll.MutableMapping
- _abcoll.Mapping
- _abcoll.Sized
- _abcoll.Iterable
- _abcoll.Container
- __builtin__.object
Methods defined here:
- __contains__(self, value)
- __delitem__(self, key)
- __getitem__(self, key)
- defines self[key]
- __init__(self, *args, **kwargs)
- __iter__(self)
- __len__(self)
- __setitem__(self, key, value)
- defines self[key] = value
Data and other attributes defined here:
- __abstractmethods__ = frozenset([])
Methods inherited from _abcoll.MutableMapping:
- clear(self)
- pop(self, key, default=<object object>)
- popitem(self)
- setdefault(self, key, default=None)
- update(*args, **kwds)
Methods inherited from _abcoll.Mapping:
- __eq__(self, other)
- __ne__(self, other)
- get(self, key, default=None)
- items(self)
- iteritems(self)
- iterkeys(self)
- itervalues(self)
- keys(self)
- values(self)
Data and other attributes inherited from _abcoll.Mapping:
- __hash__ = None
Class methods inherited from _abcoll.Sized:
- __subclasshook__(cls, C) from abc.ABCMeta
Data descriptors inherited from _abcoll.Sized:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Data and other attributes inherited from _abcoll.Sized:
- __metaclass__ = <class 'abc.ABCMeta'>
- Metaclass for defining Abstract Base Classes (ABCs).
Use this metaclass to create an ABC. An ABC can be subclassed
directly, and then acts as a mix-in class. You can also register
unrelated concrete classes (even built-in classes) and unrelated
ABCs as 'virtual subclasses' -- these and their descendants will
be considered subclasses of the registering ABC by the built-in
issubclass() function, but the registering ABC won't show up in
their MRO (Method Resolution Order) nor will method
implementations defined by the registering ABC be callable (not
even via super()).
class ElapsedTime(__builtin__.object) 32-bit C overflows after int(2**32/1e6) == 4294s about 72 min
Methods defined here:
- __call__(self)
- __init__(self)
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class FitnessFunctions(__builtin__.object) versatile container for test objective functions
Methods defined here:
- __init__(self)
- branin(self, x)
- cigar(self, x, rot=0)
- Cigar test objective function
- cigtab(self, y)
- Cigtab test objective function
- cornerelli(self, x)
- cornerellirot(self, x)
- cornersphere(self, x)
- Sphere (squared norm) test objective function constraint to the corner
- diffpow(self, x, rot=0)
- Diffpow test objective function
- elli(self, x, rot=0, xoffset=0, cond=1000000.0, actuator_noise=0.0, both=False)
- Ellipsoid test objective function
- elliconstraint(self, x, cfac=100000000.0, tough=True, cond=1000000.0)
- ellipsoid test objective function with "constraints"
- ellirot(self, x)
- elliwithoneconstraint(self, x, idx=[-1])
- flat(self, x)
- goldsteinprice(self, x)
- griewank(self, x)
- hyperelli(self, x)
- lincon(self, x, theta=0.01)
- ridge like linear function with one linear constraint
- linear(self, x)
- lineard(self, x)
- noise(self, x, func=<function sphere>, fac=10, expon=1)
- noiseC(self, x, func=<function sphere>, fac=10, expon=0.8)
- noisysphere(self, x, noise=5.0)
- normalSkew(self, f)
- optprob(self, x)
- partsphere(self, x)
- Sphere (squared norm) test objective function
- rand(self, x)
- Random test objective function
- rastrigin(self, x)
- Rastrigin test objective function
- ridge(self, x, expo=2)
- ridgecircle(self, x, expo=0.5)
- happy cat by HG Beyer
- rosen(self, x)
- Rosenbrock test objective function
- rot(self, x, fun, rot=1, args=())
- returns ``fun(rotation(x), *args)``, ie. `fun` applied to a rotated argument
- schwefelelli(self, x)
- schwefelmult(self, x, pen_fac=10000.0)
- multimodal Schwefel function with domain -500..500
- sectorsphere(self, x)
- asymmetric Sphere (squared norm) test objective function
- somenan(self, x, fun, p=0.1)
- returns sometimes np.NaN, otherwise fun(x)
- sphere(self, x)
- Sphere (squared norm) test objective function
- spherew(self, x)
- Sphere (squared norm) with sum x_i = 1 test objective function
- spherewithnconstraints(self, x)
- spherewithoneconstraint(self, x)
- tablet(self, x, rot=0)
- Tablet test objective function
- twoaxes(self, y)
- Cigtab test objective function
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class GenoPheno(__builtin__.object) Genotype-phenotype transformation.
Method `pheno` provides the transformation from geno- to phenotype,
that is from the internal representation to the representation used
in the objective function. Method `geno` provides the "inverse" pheno-
to genotype transformation. The geno-phenotype transformation comprises,
in this order:
- insert fixed variables (with the phenotypic and therefore quite
possibly "wrong" values)
- affine linear transformation (scaling and shift)
- user-defined transformation
- projection into feasible domain (boundaries)
- assign fixed variables their original phenotypic value
By default all transformations are the identity. The boundary
transformation is only applied, if the boundaries are given as argument to
the method `pheno` or `geno` respectively.
``geno`` is not really necessary and might disappear in future.
Methods defined here:
- __init__(self, dim, scaling=None, typical_x=None, bounds=None, fixed_values=None, tf=None)
- return `GenoPheno` instance with fixed dimension `dim`.
Keyword Arguments
-----------------
`scaling`
the diagonal of a scaling transformation matrix, multipliers
in the genotyp-phenotyp transformation, see `typical_x`
`typical_x`
``pheno = scaling*geno + typical_x``
`bounds` (obsolete, might disappear)
list with two elements,
lower and upper bounds both can be a scalar or a "vector"
of length dim or `None`. Without effect, as `bounds` must
be given as argument to `pheno()`.
`fixed_values`
a dictionary of variable indices and values, like ``{0:2.0, 2:1.1}``,
that a not subject to change, negative indices are dropped
(they act like incommenting the index), values are phenotypic
values.
`tf`
list of two user-defined transformation functions, or `None`.
``tf[0]`` is a function that transforms the internal representation
as used by the optimizer into a solution as used by the
objective function. ``tf[1]`` does the back-transformation.
For example ::
tf_0 = lambda x: [xi**2 for xi in x]
tf_1 = lambda x: [abs(xi)**0.5 fox xi in x]
or "equivalently" without the `lambda` construct ::
def tf_0(x):
return [xi**2 for xi in x]
def tf_1(x):
return [abs(xi)**0.5 fox xi in x]
``tf=[tf_0, tf_1]`` is a reasonable way to guaranty that only positive
values are used in the objective function.
Details
-------
In future it might be possible to omit `tf_1`
- geno(self, y, bounds=None, copy=True, copy_always=False, archive=None)
- maps the phenotypic input argument into the genotypic space.
If `bounds` are given, first `y` is projected into the feasible
domain. In this case ``copy==False`` leads to a copy.
by default a copy is made only to prevent to modify ``y``
method geno is only needed if external solutions are injected
(geno(initial_solution) is depreciated and will disappear)
TODO: arg copy=True should become copy_never=False
- into_bounds(self, y, bounds=None, copy_never=False, copy_always=False)
- Argument `y` is a phenotypic vector,
return `y` put into boundaries, as a copy iff ``y != into_bounds(y)``.
Note: this code is duplicated in `Solution.repair` and might
disappear in future.
- pheno(self, x, bounds=None, copy=True, copy_always=False)
- maps the genotypic input argument into the phenotypic space,
boundaries are only applied if argument ``bounds is not None``, see
help for class `GenoPheno`
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class GenoPhenoBase(__builtin__.object) depreciated, abstract base class for genotyp-phenotype transformation,
to be implemented.
See (and rather use) option ``transformation`` of ``fmin`` or ``CMAEvolutionStrategy``.
Example
-------
::
import cma
class Mygpt(cma.GenoPhenoBase):
def pheno(self, x):
return x # identity for the time being
gpt = Mygpt()
optim = cma.CMAEvolutionStrategy(...)
while not optim.stop():
X = optim.ask()
f = [func(gpt.pheno(x)) for x in X]
optim.tell(X, f)
In case of a repair, we might pass the repaired solution into `tell()`
(with check_points being True).
TODO: check usecases in `CMAEvolutionStrategy` and implement option GenoPhenoBase
Methods defined here:
- pheno(self, x)
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Mh = class MathHelperFunctions(__builtin__.object) static convenience math helper functions, if the function name
is preceded with an "a", a numpy array is returned
Static methods defined here:
- aclamp(x, upper)
- amax(vec, vec_or_scalar)
- amin(vec_or_scalar, vec_or_scalar2)
- apos(x, lower=0)
- clips argument (scalar or array) from below at lower
- cauchy_with_variance_one()
- expms(A, eig=<function eigh>)
- matrix exponential for a symmetric matrix
- max(vec, vec_or_scalar)
- min(a, b)
- norm(vec, expo=2)
- prctile(data, p_vals=[0, 25, 50, 75, 100], sorted_=False)
- ``prctile(data, 50)`` returns the median, but p_vals can
also be a sequence.
Provides for small samples better values than matplotlib.mlab.prctile,
however also slower.
- sround(nb)
- return stochastic round: floor(nb) + (rand()<remainder(nb))
- standard_finite_cauchy(size=1)
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class Misc(__builtin__.object) Static methods defined here:
- eig(C)
- eigendecomposition of a symmetric matrix, much slower than
`numpy.linalg.eigh`, return ``(EVals, Basis)``, the eigenvalues
and an orthonormal basis of the corresponding eigenvectors, where
``Basis[i]``
the i-th row of ``Basis``
columns of ``Basis``, ``[Basis[j][i] for j in range(len(Basis))]``
the i-th eigenvector with eigenvalue ``EVals[i]``
- likelihood(x, m=None, Cinv=None, sigma=1, detC=None)
- return likelihood of x for the normal density N(m, sigma**2 * Cinv**-1)
- loglikelihood(self, x, previous=False)
- return log-likelihood of `x` regarding the current sample distribution
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Data and other attributes defined here:
- MathHelperFunctions = <class 'cma.MathHelperFunctions'>
- static convenience math helper functions, if the function name
is preceded with an "a", a numpy array is returned
class NoiseHandler(__builtin__.object) Noise handling according to [Hansen et al 2009, A Method for Handling
Uncertainty in Evolutionary Optimization...]
The interface of this class is yet versatile and subject to changes.
The attribute ``evaluations`` serves to control the noise via number of
evaluations, for example with `ask_and_eval()`, see also parameter
``maxevals`` and compare the example.
Example
-------
>>> import cma, numpy as np
>>> func = cma.Fcts.noisysphere
>>> es = cma.CMAEvolutionStrategy(np.ones(10), 1)
>>> logger = cma.CMADataLogger().register(es)
>>> nh = cma.NoiseHandler(es.N, maxevals=[1, 30])
>>> while not es.stop():
... X, fit = es.ask_and_eval(func, evaluations=nh.evaluations)
... es.tell(X, fit) # prepare for next iteration
... es.sigma *= nh(X, fit, func, es.ask) # see method __call__
... es.countevals += nh.evaluations_just_done # this is a hack, not important though
... logger.add(more_data = [nh.evaluations, nh.noiseS]) # add a data point
... es.disp()
... # nh.maxevals = ... it might be useful to start with smaller values and then increase
>>> print(es.stop())
>>> print(es.result()[-2]) # take mean value, the best solution is totally off
>>> assert sum(es.result()[-2]**2) < 1e-9
>>> print(X[np.argmin(fit)]) # not bad, but probably worse than the mean
>>> logger.plot()
The noise options of `fmin()` control a `NoiseHandler` instance similar to this
example. The command ``cma.Options('noise')`` lists in effect the parameters of
`__init__` apart from ``aggregate``.
Details
-------
The parameters reevals, theta, c_s, and alpha_t are set differently
than in the original publication, see method `__init__()`. For a
very small population size, say popsize <= 5, the measurement
technique based on rank changes is likely to fail.
Missing Features
----------------
In case no noise is found, ``self.lam_reeval`` should be adaptive
and get at least as low as 1 (however the possible savings from this
are rather limited). Another option might be to decide during the
first call by a quantitative analysis of fitness values whether
``lam_reeval`` is set to zero. More generally, an automatic noise
mode detection might also set the covariance matrix learning rates
to smaller values.
:See: `fmin()`, `ask_and_eval()`
Methods defined here:
- __call__(self, X, fit, func, ask=None, args=())
- proceed with noise measurement, set anew attributes ``evaluations``
(proposed number of evaluations to "treat" noise) and ``evaluations_just_done``
and return a factor for increasing sigma.
Parameters
----------
`X`
a list/sequence/vector of solutions
`fit`
the respective list of function values
`func`
the objective function, ``fit[i]`` corresponds to ``func(X[i], *args)``
`ask`
a method to generate a new, slightly disturbed solution. The argument
is mandatory if ``epsilon`` is not zero, see `__init__()`.
`args`
optional additional arguments to `func`
Details
-------
Calls the methods ``reeval()``, ``update_measure()`` and ``treat()`` in this order.
``self.evaluations`` is adapted within the method `treat()`.
- __init__(self, N, maxevals=10, aggregate=<function median>, reevals=None, epsilon=1e-07)
- parameters are
`maxevals`
maximal value for ``self.evaluations``, where
``self.evaluations`` function calls are aggregated for
noise treatment. With ``maxevals == 0`` the noise
handler is (temporarily) "switched off". If `maxevals`
is a list, min value and (for >2 elements) median are
used to define minimal and initial value of
``self.evaluations``. Choosing ``maxevals > 1`` is only
reasonable, if also the original ``fit`` values (that
are passed to `__call__`) are computed by aggregation of
``self.evaluations`` values (otherwise the values are
not comparable), as it is done within `fmin()`.
`aggregate`
function to aggregate single f-values to a 'fitness', e.g.
``np.median``.
`reevals`
number of solutions to be reevaluated for noise measurement,
can be a float, by default set to ``1.5 + popsize/20``,
zero switches noise handling off.
`epsilon`
multiplier for perturbation of the reevaluated solutions
:See: `fmin()`, `Options`, `CMAEvolutionStrategy.ask_and_eval()`
- get_evaluations(self)
- return ``self.evaluations``, the number of evalutions to get a single fitness measurement
- indices(self, fit)
- return the set of indices to be reevaluted for noise measurement,
taking the ``lam_reeval`` best from the first ``2 * lam_reeval + 2``
values.
Given the first values are the earliest, this is a useful policy also
with a time changing objective.
- reeval(self, X, fit, func, ask, args=())
- store two fitness lists, `fit` and ``fitre`` reevaluating some
solutions in `X`.
``self.evaluations`` evaluations are done for each reevaluated
fitness value.
See `__call__()`, where `reeval()` is called.
- treat(self)
- adapt self.evaluations and return ``sigma_fac in (1.0, self.alphasigma)``
- update_measure(self)
- updated noise level measure using two fitness lists ``self.fit`` and
``self.fitre``, return ``self.noiseS, all_individual_measures``.
Assumes that `self.idx` contains the indices where the fitness
lists differ
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class OOOptimizer(__builtin__.object) "abstract" base class for an OO optimizer interface with methods
`__init__`, `ask`, `tell`, `stop`, `result`, and `optimize`. Only
`optimize` is fully implemented in this base class.
Examples
--------
All examples minimize the function `elli`, the output is not shown.
(A preferred environment to execute all examples is ``ipython -pylab``.)
First we need ::
from cma import CMAEvolutionStrategy, CMADataLogger # CMAEvolutionStrategy derives from the OOOptimizer class
elli = lambda x: sum(1e3**((i-1.)/(len(x)-1.)*x[i])**2 for i in range(len(x)))
The shortest example uses the inherited method `OOOptimizer.optimize()`::
res = CMAEvolutionStrategy(8 * [0.1], 0.5).optimize(elli)
The input parameters to `CMAEvolutionStrategy` are specific to this
inherited class. The remaining functionality is based on interface
defined by `OOOptimizer`. We might have a look at the result::
print(res[0]) # best solution and
print(res[1]) # its function value
`res` is the return value from method
`CMAEvolutionStrategy.result()` appended with `None` (no logger).
In order to display more exciting output we rather do ::
logger = CMADataLogger() # derives from the abstract BaseDataLogger class
res = CMAEvolutionStrategy(9 * [0.5], 0.3).optimize(elli, logger)
logger.plot() # if matplotlib is available, logger == res[-1]
or even shorter ::
res = CMAEvolutionStrategy(9 * [0.5], 0.3).optimize(elli, CMADataLogger())
res[-1].plot() # if matplotlib is available
Virtually the same example can be written with an explicit loop
instead of using `optimize()`. This gives the necessary insight into
the `OOOptimizer` class interface and gives entire control over the
iteration loop::
optim = CMAEvolutionStrategy(9 * [0.5], 0.3) # a new CMAEvolutionStrategy instance calling CMAEvolutionStrategy.__init__()
logger = CMADataLogger(optim) # get a logger instance
# this loop resembles optimize()
while not optim.stop(): # iterate
X = optim.ask() # get candidate solutions
f = [elli(x) for x in X] # evaluate solutions
# maybe do something else that needs to be done
optim.tell(X, f) # do all the real work: prepare for next iteration
optim.disp(20) # display info every 20th iteration
logger.add() # log another "data line"
# final output
print('termination by', optim.stop())
print('best f-value =', optim.result()[1])
print('best solution =', optim.result()[0])
logger.plot() # if matplotlib is available
raw_input('press enter to continue') # prevents exiting and closing figures
Details
-------
Most of the work is done in the method `tell(...)`. The method `result()` returns
more useful output.
Methods defined here:
- __init__(self, xstart, **more_args)
- abstract method, ``xstart`` is a mandatory argument
- ask(self)
- abstract method, AKA "get", deliver new candidate solution(s), a list of "vectors"
- disp(self, modulo=None)
- abstract method, display some iteration infos if ``self.iteration_counter % modulo == 0``
- initialize(self)
- (re-)set to the initial state
- optimize(self, objectivefct, logger=None, verb_disp=20, iterations=None)
- find minimizer of `objectivefct` by iterating over `OOOptimizer` `self`
with verbosity `verb_disp`, using `BaseDataLogger` `logger` with at
most `iterations` iterations. ::
return result() + (stop(), self, logger)
Example
-------
>>> import cma
>>> res = cma.CMAEvolutionStrategy(7 * [0.1], 0.5).optimize(cma.fcts.rosen, None, 100)
(4_w,9)-CMA-ES (mu_w=2.8,w_1=49%) in dimension 7 (seed=630721393)
Iterat #Fevals function value axis ratio sigma minstd maxstd min:sec
1 9 3.163954777181882e+01 1.0e+00 4.12e-01 4e-01 4e-01 0:0.0
2 18 3.299006223906629e+01 1.0e+00 3.60e-01 3e-01 4e-01 0:0.0
3 27 1.389129389866704e+01 1.1e+00 3.18e-01 3e-01 3e-01 0:0.0
100 900 2.494847340045985e+00 8.6e+00 5.03e-02 2e-02 5e-02 0:0.3
200 1800 3.428234862999135e-01 1.7e+01 3.77e-02 6e-03 3e-02 0:0.5
300 2700 3.216640032470860e-04 5.6e+01 6.62e-03 4e-04 9e-03 0:0.8
400 3600 6.155215286199821e-12 6.6e+01 7.44e-06 1e-07 4e-06 0:1.1
438 3942 1.187372505161762e-14 6.0e+01 3.27e-07 4e-09 9e-08 0:1.2
438 3942 1.187372505161762e-14 6.0e+01 3.27e-07 4e-09 9e-08 0:1.2
('termination by', {'tolfun': 1e-11})
('best f-value =', 1.1189867885201275e-14)
('solution =', array([ 1. , 1. , 1. , 0.99999999, 0.99999998,
0.99999996, 0.99999992]))
>>> print(res[0])
[ 1. 1. 1. 0.99999999 0.99999998 0.99999996
0.99999992]
- result(self)
- abstract method, return ``(x, f(x), ...)``, that is, the minimizer, its function value, ...
- stop(self)
- abstract method, return satisfied termination conditions in a dictionary like
``{'termination reason': value, ...}``, for example ``{'tolfun': 1e-12}``, or the empty
dictionary ``{}``. The implementation of `stop()` should prevent an infinite loop.
- tell(self, solutions, function_values)
- abstract method, AKA "update", prepare for next iteration
Static methods defined here:
- abstract()
- marks a method as abstract, ie to be implemented by a subclass
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class Options(__builtin__.dict) ``Options()`` returns a dictionary with the available options and their
default values for function fmin and for class CMAEvolutionStrategy.
``Options(opts)`` returns the subset of recognized options in dict(opts).
``Options('pop')`` returns a subset of recognized options that contain
'pop' in there keyword name, value or description.
Option values can be "written" in a string and, when passed to fmin
or CMAEvolutionStrategy, are evaluated using "N" and "popsize" as
known values for dimension and population size (sample size, number
of new solutions per iteration). All default option values are such
a string.
Details
-------
All Options are originally defined via the input arguments of
`fmin()`.
Options starting with ``tol`` are termination "tolerances".
For `tolstagnation`, the median over the first and the second half
of at least `tolstagnation` iterations are compared for both, the
per-iteration best and per-iteration median function value.
Some options are, as mentioned (`restarts`,...), only used with `fmin`.
Example
-------
::
import cma
cma.Options('tol')
is a shortcut for cma.Options().match('tol') that returns all options
that contain 'tol' in their name or description.
:See: `fmin`(), `CMAEvolutionStrategy`, `CMAParameters`
- Method resolution order:
- Options
- __builtin__.dict
- __builtin__.object
Methods defined here:
- __call__(self, key, default=None, loc=None)
- evaluate and return the value of option `key` on the fly, or
returns those options whose name or description contains `key`,
case disregarded.
Details
-------
Keys that contain `filename` are not evaluated.
For ``loc==None``, `self` is used as environment
but this does not define `N`.
:See: `eval()`, `evalall()`
- __init__(self, s=None, unchecked=False)
- return an `Options` instance, either with the default options,
if ``s is None``, or with all options whose name or description
contains `s`, if `s` is a string (case is disregarded),
or with entries from dictionary `s` as options, not complemented
with default options or settings
Returns: see above.
- complement(self)
- add all missing options with their default values
- divCroot(self, mat)
- return C**-1/2 times mat, where mat can be a vector or matrix
- eval(self, key, default=None, loc=None)
- Evaluates and sets the specified option value in
environment `loc`. Many options need `N` to be defined in
`loc`, some need `popsize`.
Details
-------
Keys that contain 'filename' are not evaluated.
For `loc` is None, the self-dict is used as environment
:See: `evalall()`, `__call__`
- evalall(self, loc=None)
- Evaluates all option values in environment `loc`.
:See: `eval()`
- init(self, dict_or_str, val=None, warn=True)
- initialize one or several options.
Arguments
---------
`dict_or_str`
a dictionary if ``val is None``, otherwise a key.
If `val` is provided `dict_or_str` must be a valid key.
`val`
value for key
Details
-------
Only known keys are accepted. Known keys are in `Options.defaults()`
- match(self, s='')
- return all options that match, in the name or the description,
with string `s`, case is disregarded.
Example: ``cma.Options().match('verb')`` returns the verbosity options.
- pp(self)
- printme(self, linebreak=80)
- set(self, dic, val=None, warn=True)
- set can assign versatile options from `Options.versatileOptions()`
with a new value, use `init()` for the others.
Arguments
---------
`dic`
either a dictionary or a key. In the latter
case, val must be provided
`val`
value for key
`warn`
bool, print a warning if the option cannot be changed
and is therefore omitted
This method will be most probably used with the ``opts`` attribute of
a `CMAEvolutionStrategy` instance.
- settable(self)
- return the subset of those options that are settable at any
time.
Settable options are in `versatileOptions()`, but the
list might be incomlete.
- timesCroot(self, mat)
- return C**0.5 times mat, where mat can be a vector or matrix.
Not functional, because _Croot=C**0.5 is never computed (should be in updateBD)
Static methods defined here:
- defaults()
- return a dictionary with default option values and description,
calls `fmin([], [])`
- versatileOptions()
- return list of options that can be changed at any time (not only be
initialized), however the list might not be entirely up to date. The
string ' #v ' in the default value indicates a 'versatile' option
that can be changed any time.
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Methods inherited from __builtin__.dict:
- __cmp__(...)
- x.__cmp__(y) <==> cmp(x,y)
- __contains__(...)
- D.__contains__(k) -> True if D has a key k, else False
- __delitem__(...)
- x.__delitem__(y) <==> del x[y]
- __eq__(...)
- x.__eq__(y) <==> x==y
- __ge__(...)
- x.__ge__(y) <==> x>=y
- __getattribute__(...)
- x.__getattribute__('name') <==> x.name
- __getitem__(...)
- x.__getitem__(y) <==> x[y]
- __gt__(...)
- x.__gt__(y) <==> x>y
- __iter__(...)
- x.__iter__() <==> iter(x)
- __le__(...)
- x.__le__(y) <==> x<=y
- __len__(...)
- x.__len__() <==> len(x)
- __lt__(...)
- x.__lt__(y) <==> x<y
- __ne__(...)
- x.__ne__(y) <==> x!=y
- __repr__(...)
- x.__repr__() <==> repr(x)
- __setitem__(...)
- x.__setitem__(i, y) <==> x[i]=y
- __sizeof__(...)
- D.__sizeof__() -> size of D in memory, in bytes
- clear(...)
- D.clear() -> None. Remove all items from D.
- copy(...)
- D.copy() -> a shallow copy of D
- get(...)
- D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
- has_key(...)
- D.has_key(k) -> True if D has a key k, else False
- items(...)
- D.items() -> list of D's (key, value) pairs, as 2-tuples
- iteritems(...)
- D.iteritems() -> an iterator over the (key, value) items of D
- iterkeys(...)
- D.iterkeys() -> an iterator over the keys of D
- itervalues(...)
- D.itervalues() -> an iterator over the values of D
- keys(...)
- D.keys() -> list of D's keys
- pop(...)
- D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
- popitem(...)
- D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
- setdefault(...)
- D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
- update(...)
- D.update(E, **F) -> None. Update D from dict/iterable E and F.
If E has a .keys() method, does: for k in E: D[k] = E[k]
If E lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
- values(...)
- D.values() -> list of D's values
- viewitems(...)
- D.viewitems() -> a set-like object providing a view on D's items
- viewkeys(...)
- D.viewkeys() -> a set-like object providing a view on D's keys
- viewvalues(...)
- D.viewvalues() -> an object providing a view on D's values
Data and other attributes inherited from __builtin__.dict:
- __hash__ = None
- __new__ = <built-in method __new__ of type object>
- T.__new__(S, ...) -> a new object with type S, a subtype of T
- fromkeys = <built-in method fromkeys of type object>
- dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
class Rotation(__builtin__.object) Rotation class that implements an orthogonal linear transformation,
one for each dimension. Used to implement non-separable test functions.
Example:
>>> import cma, numpy as np
>>> R = cma.Rotation()
>>> R2 = cma.Rotation() # another rotation
>>> x = np.array((1,2,3))
>>> print(R(R(x), inverse=1))
[ 1. 2. 3.]
Methods defined here:
- __call__(self, x, inverse=False)
- Rotates the input array `x` with a fixed rotation matrix
(``self.dicMatrices['str(len(x))']``)
- __init__(self)
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Data and other attributes defined here:
- dicMatrices = {}
class Sections(__builtin__.object) plot sections through an objective function. A first
rational thing to do, when facing an (expensive) application.
By default 6 points in each coordinate are evaluated.
This class is still experimental.
Examples
--------
>>> import cma, numpy as np
>>> s = cma.Sections(cma.Fcts.rosen, np.zeros(3)).do(plot=False)
>>> s.do(plot=False) # evaluate the same points again, i.e. check for noise
>>> try:
... s.plot()
... except:
... print('plotting failed: pylab package is missing?')
Details
-------
Data are saved after each function call during `do()`. The filename is attribute
``name`` and by default ``str(func)``, see `__init__()`.
A random (orthogonal) basis can be generated with ``cma.Rotation()(np.eye(3))``.
The default name is unique in the function name, but it should be unique in all
parameters of `__init__()` but `plot_cmd` and `load`.
``self.res`` is a dictionary with an entry for each "coordinate" ``i`` and with an
entry ``'x'``, the middle point. Each entry ``i`` is again a dictionary with keys
being different dx values and the value being a sequence of f-values.
For example ``self.res[2][0.1] == [0.01, 0.01]``, which is generated using the
difference vector ``self.basis[2]`` like
``self.res[2][dx] += func(self.res['x'] + dx * self.basis[2])``.
:See: `__init__()`
Methods defined here:
- __init__(self, func, x, args=(), basis=None, name=None, plot_cmd=<function plot>, load=True)
- Parameters
----------
`func`
objective function
`x`
point in search space, middle point of the sections
`args`
arguments passed to `func`
`basis`
evaluated points are ``func(x + locations[j] * basis[i]) for i in len(basis) for j in len(locations)``,
see `do()`
`name`
filename where to save the result
`plot_cmd`
command used to plot the data, typically matplotlib pylabs `plot` or `semilogy`
`load`
load previous data from file ``str(func) + '.pkl'``
- do(self, repetitions=1, locations=array([-0.5, -0.3, -0.1, 0.1, 0.3, 0.5]), plot=True)
- generates, plots and saves function values ``func(y)``,
where ``y`` is 'close' to `x` (see `__init__()`). The data are stored in
the ``res`` attribute and the class instance is saved in a file
with (the weired) name ``str(func)``.
Parameters
----------
`repetitions`
for each point, only for noisy functions is >1 useful. For
``repetitions==0`` only already generated data are plotted.
`locations`
coordinated wise deviations from the middle point given in `__init__`
- flattened(self)
- return flattened data ``(x, f)`` such that for the sweep through
coordinate ``i`` we have for data point ``j`` that ``f[i][j] == func(x[i][j])``
- load(self, name=None)
- load from file
- plot(self, plot_cmd=None, tf=<function <lambda>>)
- plot the data we have, return ``self``
- save(self, name=None)
- save to file
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
class SolutionDict(DerivedDictBase) dictionary with computation of an hash key for the inserted solutions and
stack of previously inserted same solutions.
Each entry is meant to store additional information related to the solution.
d = SolutionDict()
x = array([1,2,4])
d[x] = {'x': x, 'iteration': 1}
d.get(x) == d[x] if d.key(x) in d.keys() else d.get(x) is None
TODO: not yet tested
TODO: data_with_same_key behaves like a stack (see setitem and delitem), but rather should behave like a queue?!
A queue is less consistent with the operation self[key] = ..., if self.data_with_same_key[key] is not empty.
- Method resolution order:
- SolutionDict
- DerivedDictBase
- _abcoll.MutableMapping
- _abcoll.Mapping
- _abcoll.Sized
- _abcoll.Iterable
- _abcoll.Container
- __builtin__.object
Methods defined here:
- __delitem__(self, key)
- remove only most current key-entry
- __getitem__(self, key)
- defines self[key]
- __init__(self, *args, **kwargs)
- __setitem__(self, key, value)
- defines self[key] = value
- key(self, x)
- truncate(self, max_len, min_iter)
Data and other attributes defined here:
- __abstractmethods__ = frozenset([])
Methods inherited from DerivedDictBase:
- __contains__(self, value)
- __iter__(self)
- __len__(self)
Methods inherited from _abcoll.MutableMapping:
- clear(self)
- pop(self, key, default=<object object>)
- popitem(self)
- setdefault(self, key, default=None)
- update(*args, **kwds)
Methods inherited from _abcoll.Mapping:
- __eq__(self, other)
- __ne__(self, other)
- get(self, key, default=None)
- items(self)
- iteritems(self)
- iterkeys(self)
- itervalues(self)
- keys(self)
- values(self)
Data and other attributes inherited from _abcoll.Mapping:
- __hash__ = None
Class methods inherited from _abcoll.Sized:
- __subclasshook__(cls, C) from abc.ABCMeta
Data descriptors inherited from _abcoll.Sized:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Data and other attributes inherited from _abcoll.Sized:
- __metaclass__ = <class 'abc.ABCMeta'>
- Metaclass for defining Abstract Base Classes (ABCs).
Use this metaclass to create an ABC. An ABC can be subclassed
directly, and then acts as a mix-in class. You can also register
unrelated concrete classes (even built-in classes) and unrelated
ABCs as 'virtual subclasses' -- these and their descendants will
be considered subclasses of the registering ABC by the built-in
issubclass() function, but the registering ABC won't show up in
their MRO (Method Resolution Order) nor will method
implementations defined by the registering ABC be callable (not
even via super()).
class SolutionDictOld(__builtin__.dict) depreciated, SolutionDict should do, to be removed after SolutionDict
has been successfully applied.
dictionary with computation of an hash key for the inserted solutions and
stack of previously inserted same solutions.
Each entry is meant to store additional information related to the solution.
Methods ``pop`` and ``get`` are modified accordingly.
d = SolutionDict()
x = array([1,2,4])
d.insert(x, {'x': x, 'iteration': 1})
d.get(x) == d[d.key(x)] if d.key(x) in d.keys() else d.get(x) is None
TODO: not yet tested
TODO: behaves like a stack (see _pop_derived), but rather should behave like a queue?!
A queue is less consistent with the operation self[key] = ..., if self.more[key] is not empty.
- Method resolution order:
- SolutionDictOld
- __builtin__.dict
- __builtin__.object
Methods defined here:
- __init__(self)
- insert(self, x, datadict)
- key(self, x)
- compute the hash key of ``x``
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Methods inherited from __builtin__.dict:
- __cmp__(...)
- x.__cmp__(y) <==> cmp(x,y)
- __contains__(...)
- D.__contains__(k) -> True if D has a key k, else False
- __delitem__(...)
- x.__delitem__(y) <==> del x[y]
- __eq__(...)
- x.__eq__(y) <==> x==y
- __ge__(...)
- x.__ge__(y) <==> x>=y
- __getattribute__(...)
- x.__getattribute__('name') <==> x.name
- __getitem__(...)
- x.__getitem__(y) <==> x[y]
- __gt__(...)
- x.__gt__(y) <==> x>y
- __iter__(...)
- x.__iter__() <==> iter(x)
- __le__(...)
- x.__le__(y) <==> x<=y
- __len__(...)
- x.__len__() <==> len(x)
- __lt__(...)
- x.__lt__(y) <==> x<y
- __ne__(...)
- x.__ne__(y) <==> x!=y
- __repr__(...)
- x.__repr__() <==> repr(x)
- __setitem__(...)
- x.__setitem__(i, y) <==> x[i]=y
- __sizeof__(...)
- D.__sizeof__() -> size of D in memory, in bytes
- clear(...)
- D.clear() -> None. Remove all items from D.
- copy(...)
- D.copy() -> a shallow copy of D
- get(...)
- D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
- has_key(...)
- D.has_key(k) -> True if D has a key k, else False
- items(...)
- D.items() -> list of D's (key, value) pairs, as 2-tuples
- iteritems(...)
- D.iteritems() -> an iterator over the (key, value) items of D
- iterkeys(...)
- D.iterkeys() -> an iterator over the keys of D
- itervalues(...)
- D.itervalues() -> an iterator over the values of D
- keys(...)
- D.keys() -> list of D's keys
- pop(...)
- D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
- popitem(...)
- D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
- setdefault(...)
- D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
- update(...)
- D.update(E, **F) -> None. Update D from dict/iterable E and F.
If E has a .keys() method, does: for k in E: D[k] = E[k]
If E lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
- values(...)
- D.values() -> list of D's values
- viewitems(...)
- D.viewitems() -> a set-like object providing a view on D's items
- viewkeys(...)
- D.viewkeys() -> a set-like object providing a view on D's keys
- viewvalues(...)
- D.viewvalues() -> an object providing a view on D's values
Data and other attributes inherited from __builtin__.dict:
- __hash__ = None
- __new__ = <built-in method __new__ of type object>
- T.__new__(S, ...) -> a new object with type S, a subtype of T
- fromkeys = <built-in method fromkeys of type object>
- dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
class TimeIt(__builtin__.object) #____________________________________________________________
#____________________________________________________________
Methods defined here:
- __init__(self, fct, args=(), seconds=1)
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Functions
- array(...)
- array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
Create an array.
Parameters
----------
object : array_like
An array, any object exposing the array interface, an
object whose __array__ method returns an array, or any
(nested) sequence.
dtype : data-type, optional
The desired data-type for the array. If not given, then
the type will be determined as the minimum type required
to hold the objects in the sequence. This argument can only
be used to 'upcast' the array. For downcasting, use the
.astype(t) method.
copy : bool, optional
If true (default), then the object is copied. Otherwise, a copy
will only be made if __array__ returns a copy, if obj is a
nested sequence, or if a copy is needed to satisfy any of the other
requirements (`dtype`, `order`, etc.).
order : {'C', 'F', 'A'}, optional
Specify the order of the array. If order is 'C' (default), then the
array will be in C-contiguous order (last-index varies the
fastest). If order is 'F', then the returned array
will be in Fortran-contiguous order (first-index varies the
fastest). If order is 'A', then the returned array may
be in any order (either C-, Fortran-contiguous, or even
discontiguous).
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
ndmin : int, optional
Specifies the minimum number of dimensions that the resulting
array should have. Ones will be pre-pended to the shape as
needed to meet this requirement.
Examples
--------
>>> np.array([1, 2, 3])
array([1, 2, 3])
Upcasting:
>>> np.array([1, 2, 3.0])
array([ 1., 2., 3.])
More than one dimension:
>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
[3, 4]])
Minimum dimensions 2:
>>> np.array([1, 2, 3], ndmin=2)
array([[1, 2, 3]])
Type provided:
>>> np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j, 2.+0.j, 3.+0.j])
Data-type consisting of more than one element:
>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])
Creating an array from sub-classes:
>>> np.array(np.mat('1 2; 3 4'))
array([[1, 2],
[3, 4]])
>>> np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
[3, 4]])
- disp(name=None, idx=None)
- displays selected data from (files written by) the class `CMADataLogger`.
The call ``cma.disp(name, idx)`` is a shortcut for ``cma.CMADataLogger(name).disp(idx)``.
Arguments
---------
`name`
name of the logger, filename prefix, `None` evaluates to
the default ``'outcmaes'``
`idx`
indices corresponding to rows in the data file; by
default the first five, then every 100-th, and the last
10 rows. Too large index values are removed.
Examples
--------
::
import cma, numpy
# assume some data are available from previous runs
cma.disp(None,numpy.r_[0,-1]) # first and last
cma.disp(None,numpy.r_[0:1e9:100,-1]) # every 100-th and last
cma.disp(idx=numpy.r_[0,-10:0]) # first and ten last
cma.disp(idx=numpy.r_[0:1e9:1e3,-10:0])
:See: `CMADataLogger.disp()`
- dot(...)
- dot(a, b)
Dot product of two arrays.
For 2-D arrays it is equivalent to matrix multiplication, and for 1-D
arrays to inner product of vectors (without complex conjugation). For
N dimensions it is a sum product over the last axis of `a` and
the second-to-last of `b`::
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
Parameters
----------
a : array_like
First argument.
b : array_like
Second argument.
Returns
-------
output : ndarray
Returns the dot product of `a` and `b`. If `a` and `b` are both
scalars or both 1-D arrays then a scalar is returned; otherwise
an array is returned.
Raises
------
ValueError
If the last dimension of `a` is not the same size as
the second-to-last dimension of `b`.
See Also
--------
vdot : Complex-conjugating dot product.
tensordot : Sum products over arbitrary axes.
Examples
--------
>>> np.dot(3, 4)
12
Neither argument is complex-conjugated:
>>> np.dot([2j, 3j], [2j, 3j])
(-13+0j)
For 2-D arrays it's the matrix product:
>>> a = [[1, 0], [0, 1]]
>>> b = [[4, 1], [2, 2]]
>>> np.dot(a, b)
array([[4, 1],
[2, 2]])
>>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
>>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
>>> np.dot(a, b)[2,3,2,1,2,2]
499128
>>> sum(a[2,3,2,:] * b[1,2,:,2])
499128
- fmin(func, x0, sigma0=None, args=(), CMA_active='False # exponential negative update, conducted after the original update', CMA_activefac='1 # learning rate multiplier for active update', CMA_cmean='1 # learning rate for the mean value', CMA_diagonal='0*100*N/sqrt(popsize) # nb of iterations with diagonal covariance matrix, True for always', CMA_eigenmethod='np.linalg.eigh # 0=numpy-s eigh, -1=pygsl, otherwise cma.Misc.eig (slower)', CMA_elitist='False # elitism likely impairs global search performance', CMA_mirrors='popsize < 6 # values <0.5 are interpreted as fr...s numbers (rounded), otherwise about 0.16 is used', CMA_mu='None # parents selection parameter, default is popsize // 2', CMA_on='True # False or 0 for no adaptation of the covariance matrix', CMA_rankmu='True # False or 0 for omitting rank-mu update of covariance matrix', CMA_rankmualpha='0.3 # factor of rank-mu update if mu=1, subject to removal, default might change to 0.0', CMA_dampfac='1 #v positive multiplier for step-size damping, 0.3 is close to optimal on the sphere', CMA_teststds='None # factors for non-isotropic initial distr. mainly for test purpose, see scaling_...', CMA_AII='False # not yet tested', bounds='[None, None] # lower (=bounds[0]) and upper domain boundaries, each a scalar or a list/vector', check_points='None # when repairing or injecting solutions, they should be checked (index-list or True)', eval_initial_x='False # ', fixed_variables='None # dictionary with index-value pairs like {0:1.1, 2:0.1} that are not optimized', ftarget='-inf #v target function value, minimization', incpopsize='2 # in fmin(): multiplier for increasing popsize before each restart', maxfevals='inf #v maximum number of function evaluations', maxiter='100 + 50 * (N+3)**2 // popsize**0.5 #v maximum number of iterations', mindx='0 #v minimal std in any direction, cave interference with tol*', minstd='0 #v minimal std in any coordinate direction, cave interference with tol*', noise_handling='False # maximal number of evaluations for noise treatment, only fmin', noise_reevals=' 1.5 + popsize/20 # number of solution to be reevaluated for noise measurement, only fmin', noise_eps='1e-7 # perturbation factor for noise handling reevaluations, only fmin', popsize='4+int(3*log(N)) # population size, AKA lambda, number of new solution per iteration', randn='np.random.standard_normal #v randn((lam, N)) must return an np.array of shape (lam, N)', restarts='0 # in fmin(): number of restarts', scaling_of_variables='None # scale for each variable, sigma0 is inter...iables and sigma is unchanged, default is ones(N)', seed='None # random number seed', termination_callback='None #v in fmin(): a function returning True fo...eration step and could be abused for side effects', tolfacupx='1e3 #v termination when step-size increases by ... were found far away from the initial solution x0', tolupsigma='1e20 #v sigma/sigma0 > tolupsigma * max(sqrt(ei...reeping behavior" with usually minor improvements', tolfun='1e-11 #v termination criterion: tolerance in function value, quite useful', tolfunhist='1e-12 #v termination criterion: tolerance in function value history', tolstagnation='int(100 * N**1.5 / popsize) #v termination if no improvement over tolstagnation iterations', tolx='1e-11 #v termination criterion: tolerance in x-changes', transformation='None # [t0, t1] are two mappings, t0 transforms...1 is the back transformation, see class GenoPheno', typical_x='None # used with scaling_of_variables', updatecovwait='None #v number of iterations without distribution update, name is subject to future changes', verb_append='0 # initial evaluation counter, if append, do not overwrite output files', verb_disp='100 #v verbosity: display console output every verb_disp iteration', verb_filenameprefix='outcmaes # output filenames prefix', verb_log='1 #v verbosity: write data to files every verb_...an be time critical on fast to evaluate functions', verb_plot='0 #v in fmin(): plot() is called every verb_plot iteration', verb_time='True #v output timings on console', vv="0 #? versatile variable for hacking purposes, value found in self.opts['vv']")
- functional interface to the stochastic optimizer CMA-ES
for non-convex function minimization.
Calling Sequences
=================
``fmin([],[])``
returns all optional arguments, that is,
all keyword arguments to fmin with their default values
in a dictionary.
``fmin(func, x0, sigma0)``
minimizes `func` starting at `x0` and with standard deviation
`sigma0` (step-size)
``fmin(func, x0, sigma0, ftarget=1e-5)``
minimizes `func` up to target function value 1e-5
``fmin(func, x0, sigma0, args=('f',), **options)``
minimizes `func` called with an additional argument ``'f'``.
`options` is a dictionary with additional keyword arguments, e.g.
delivered by `Options()`.
``fmin(func, x0, sigma0, **{'ftarget':1e-5, 'popsize':40})``
the same as ``fmin(func, x0, sigma0, ftarget=1e-5, popsize=40)``
``fmin(func, esobj, **{'maxfevals': 1e5})``
uses the `CMAEvolutionStrategy` object instance `esobj` to optimize
`func`, similar to `CMAEvolutionStrategy.optimize()`.
Arguments
=========
`func`
function to be minimized. Called as
``func(x,*args)``. `x` is a one-dimensional `numpy.ndarray`. `func`
can return `numpy.NaN`,
which is interpreted as outright rejection of solution `x`
and invokes an immediate resampling and (re-)evaluation
of a new solution not counting as function evaluation.
`x0`
list or `numpy.ndarray`, initial guess of minimum solution
or `cma.CMAEvolutionStrategy` object instance. In this case
`sigma0` can be omitted.
`sigma0`
scalar, initial standard deviation in each coordinate.
`sigma0` should be about 1/4 of the search domain width where the
optimum is to be expected. The variables in `func` should be
scaled such that they presumably have similar sensitivity.
See also option `scaling_of_variables`.
Keyword Arguments
=================
All arguments besides `args` and `verb_filenameprefix` are evaluated
if they are of type `str`, see class `Options` for details.
::
args=() -- additional arguments for func, not in `cma.Options()`
CMA_active='False # exponential negative update, conducted after the original
update'
CMA_activefac='1 # learning rate multiplier for active update'
CMA_cmean='1 # learning rate for the mean value'
CMA_dampfac='1 #v positive multiplier for step-size damping, 0.3 is close to
optimal on the sphere'
CMA_diagonal='0*100*N/sqrt(popsize) # nb of iterations with diagonal
covariance matrix, True for always'
CMA_eigenmethod='np.linalg.eigh # 0=numpy-s eigh, -1=pygsl, alternative: Misc.eig (slower)'
CMA_elitist='False # elitism likely impairs global search performance'
CMA_mirrors='0 # values <0.5 are interpreted as fraction, values >1 as numbers
(rounded), otherwise about 0.16 is used'
CMA_mu='None # parents selection parameter, default is popsize // 2'
CMA_on='True # False or 0 for no adaptation of the covariance matrix'
CMA_rankmu='True # False or 0 for omitting rank-mu update of covariance
matrix'
CMA_rankmualpha='0.3 # factor of rank-mu update if mu=1, subject to removal,
default might change to 0.0'
CMA_teststds='None # factors for non-isotropic initial distr. mainly for test
purpose, see scaling_...'
bounds='[None, None] # lower (=bounds[0]) and upper domain boundaries, each a
scalar or a list/vector'
check_points='None # when repairing or injecting solutions, they should be checked
(index-list or True)'
eval_initial_x='False # '
fixed_variables='None # dictionary with index-value pairs like {0:1.1, 2:0.1}
that are not optimized'
ftarget='-inf #v target function value, minimization'
incpopsize='2 # in fmin(): multiplier for increasing popsize before each
restart'
maxfevals='inf #v maximum number of function evaluations'
maxiter='long(1e3*N**2/sqrt(popsize)) #v maximum number of iterations'
mindx='0 #v minimal std in any direction, cave interference with tol*'
minstd='0 #v minimal std in any coordinate direction, cave interference with
tol*'
noise_eps='1e-7 # perturbation factor for noise handling reevaluations, only
fmin'
noise_handling='False # maximal number of evaluations for noise treatment,
only fmin'
noise_reevals=' 1.5 + popsize/20 # number of solution to be reevaluated for
noise measurement, only fmin'
popsize='4+int(3*log(N)) # population size, AKA lambda, number of new solution
per iteration'
randn='np.random.standard_normal #v randn((lam, N)) must return an np.array of
shape (lam, N)'
restarts='0 # in fmin(): number of restarts'
scaling_of_variables='None # scale for each variable, sigma0 is interpreted
w.r.t. this scale, in that effective_sigma0 = sigma0*scaling.
Internally the variables are divided by scaling_of_variables and sigma
is unchanged, default is ones(N)'
seed='None # random number seed'
termination_callback='None #v in fmin(): a function returning True for
termination, called after each iteration step and could be abused for
side effects'
tolfacupx='1e3 #v termination when step-size increases by tolfacupx
(diverges). That is, the initial step-size was chosen far too small and
better solutions were found far away from the initial solution x0'
tolupsigma='1e20 #v sigma/sigma0 > tolupsigma * max(sqrt(eivenvals(C)))
indicates "creeping behavior" with usually minor improvements'
tolfun='1e-11 #v termination criterion: tolerance in function value, quite
useful'
tolfunhist='1e-12 #v termination criterion: tolerance in function value
history'
tolstagnation='int(100 * N**1.5 / popsize) #v termination if no improvement
over tolstagnation iterations'
tolx='1e-11 #v termination criterion: tolerance in x-changes'
transformation='None # [t0, t1] are two mappings, t0 transforms solutions from
CMA-representation to f-representation, t1 is the back transformation,
see class GenoPheno'
typical_x='None # used with scaling_of_variables'
updatecovwait='None #v number of iterations without distribution update, name
is subject to future changes'
verb_append='0 # initial evaluation counter, if append, do not overwrite
output files'
verb_disp='100 #v verbosity: display console output every verb_disp iteration'
verb_filenameprefix='outcmaes # output filenames prefix'
verb_log='1 #v verbosity: write data to files every verb_log iteration,
writing can be time critical on fast to evaluate functions'
verb_plot='0 #v in fmin(): plot() is called every verb_plot iteration'
verb_time='True #v output timings on console'
vv='0 #? versatile variable for hacking purposes, value found in
self.opts['vv']'
Subsets of options can be displayed, for example like ``cma.Options('tol')``,
see also class `Options`.
Return
======
Similar to `OOOptimizer.optimize()` and/or `CMAEvolutionStrategy.optimize()`, return the
list provided by `CMAEvolutionStrategy.result()` appended with an `OOOptimizer` and an
`BaseDataLogger`::
res = optim.result() + (optim.stop(), optim, logger)
where
- ``res[0]`` (``xopt``) -- best evaluated solution
- ``res[1]`` (``fopt``) -- respective function value
- ``res[2]`` (``evalsopt``) -- respective number of function evaluations
- ``res[3]`` (``evals``) -- number of overall conducted objective function evaluations
- ``res[4]`` (``iterations``) -- number of overall conducted iterations
- ``res[5]`` (``xmean``) -- mean of the final sample distribution
- ``res[6]`` (``stds``) -- effective stds of the final sample distribution
- ``res[-3]`` (``stop``) -- termination condition(s) in a dictionary
- ``res[-2]`` (``cmaes``) -- class `CMAEvolutionStrategy` instance
- ``res[-1]`` (``logger``) -- class `CMADataLogger` instance
Details
=======
This function is an interface to the class `CMAEvolutionStrategy`. The
class can be used when full control over the iteration loop of the
optimizer is desired.
The noise handling follows closely [Hansen et al 2009, A Method for Handling
Uncertainty in Evolutionary Optimization...] in the measurement part, but the
implemented treatment is slightly different: for ``noiseS > 0``, ``evaluations``
(time) and sigma are increased by ``alpha``. For ``noiseS < 0``, ``evaluations``
(time) is decreased by ``alpha**(1/4)``. The option ``noise_handling`` switches
the uncertainty handling on/off and gives the maximal number of evaluations for
a single fitness computation. If ``noise_handling`` is a list, the smallest
element defines the minimal number and if the list has three elements, the
median value is the start value for ``evaluations``.
See also class `NoiseHandler`.
Examples
========
The following example calls `fmin` optimizing the Rosenbrock function
in 10-D with initial solution 0.1 and initial step-size 0.5. The
options are specified for the usage with the `doctest` module.
>>> import cma
>>> # cma.Options() # returns all possible options
>>> options = {'CMA_diagonal':10, 'seed':1234, 'verb_time':0}
>>>
>>> res = cma.fmin(cma.fcts.rosen, [0.1] * 10, 0.5, **options)
(5_w,10)-CMA-ES (mu_w=3.2,w_1=45%) in dimension 10 (seed=1234)
Covariance matrix is diagonal for 10 iterations (1/ccov=29.0)
Iterat #Fevals function value axis ratio sigma minstd maxstd min:sec
1 10 1.264232686260072e+02 1.1e+00 4.40e-01 4e-01 4e-01
2 20 1.023929748193649e+02 1.1e+00 4.00e-01 4e-01 4e-01
3 30 1.214724267489674e+02 1.2e+00 3.70e-01 3e-01 4e-01
100 1000 6.366683525319511e+00 6.2e+00 2.49e-02 9e-03 3e-02
200 2000 3.347312410388666e+00 1.2e+01 4.52e-02 8e-03 4e-02
300 3000 1.027509686232270e+00 1.3e+01 2.85e-02 5e-03 2e-02
400 4000 1.279649321170636e-01 2.3e+01 3.53e-02 3e-03 3e-02
500 5000 4.302636076186532e-04 4.6e+01 4.78e-03 3e-04 5e-03
600 6000 6.943669235595049e-11 5.1e+01 5.41e-06 1e-07 4e-06
650 6500 5.557961334063003e-14 5.4e+01 1.88e-07 4e-09 1e-07
termination on tolfun : 1e-11
final/bestever f-value = 5.55796133406e-14 2.62435631419e-14
mean solution: [ 1. 1.00000001 1. 1.
1. 1.00000001 1.00000002 1.00000003 ...]
std deviation: [ 3.9193387e-09 3.7792732e-09 4.0062285e-09 4.6605925e-09
5.4966188e-09 7.4377745e-09 1.3797207e-08 2.6020765e-08 ...]
>>>
>>> print('best solutions fitness = %f' % (res[1]))
best solutions fitness = 2.62435631419e-14
>>> assert res[1] < 1e-12
The method ::
cma.plot();
(based on `matplotlib.pylab`) produces a plot of the run and, if necessary::
cma.show()
shows the plot in a window. To continue you might need to
close the pop-up window. This behavior seems to disappear in
subsequent calls of `cma.plot()` and is avoided by using
`ipython` with `-pylab` option. Finally ::
cma.savefig('myfirstrun') # savefig from matplotlib.pylab
will save the figure in a png.
:See: `CMAEvolutionStrategy`, `OOOptimizer.optimize(), `plot()`, `Options`, `scipy.optimize.fmin()`
- irg(ar)
- #____________________________________________________________
#____________________________________________________________
- main(argv=None)
- provides a versatile interface to do some testing from the command line.
Usage: python cma.py [options | func dim sig0 [optkey optval][optkey optval]...]
Use option -t or --test to run the doctest, -t -v to get (much) verbosity
and -t -q to run it quietly with output only in case of errors.
Use options --fcts and --doc for more infos or start ipython --pylab.
Examples
--------
A single run: python cma.py elli 10 1
Run doctest: python cma.py --test --quiet
- plot(name=None, fig=None, abscissa=1, iteridx=None, plot_mean=True, foffset=1e-19, x_opt=None, fontsize=10)
- plot data from files written by a `CMADataLogger`,
the call ``cma.plot(name, **argsdict)`` is a shortcut for
``cma.CMADataLogger(name).plot(**argsdict)``
Arguments
---------
`name`
name of the logger, filename prefix, None evaluates to
the default 'outcmaes'
`fig`
filename or figure number, or both as a tuple (any order)
`abscissa`
0==plot versus iteration count,
1==plot versus function evaluation number
`iteridx`
iteration indices to plot
Return `None`
Examples
--------
::
cma.plot(); # the optimization might be still
# running in a different shell
cma.show() # to continue you might need to close the pop-up window
# once and call cma.plot() again.
# This behavior seems to disappear in subsequent
# calls of cma.plot(). Also using ipython with -pylab
# option might help.
cma.savefig('fig325.png')
cma.close()
cdl = cma.CMADataLogger().downsampling().plot()
Details
-------
Data from codes in other languages (C, Java, Matlab, Scilab) have the same
format and can be plotted just the same.
:See: `CMADataLogger`, `CMADataLogger.plot()`
- pprint(to_be_printed)
- nicely formated print
- process_test(stream=None)
- unitdoctest()
- is used to describe test cases and might in future become helpful
as an experimental tutorial as well. The main testing feature at the
moment is by doctest with ``cma._test()`` or conveniently by
``python cma.py --test``. Unfortunately, depending on the
system, the results will slightly differ and many "failed" test cases
might be reported. This is prevented with the --quiet option.
A simple first overall test:
>>> import cma
>>> res = cma.fmin(cma.fcts.elli, 3*[1], 1, CMA_diagonal=2, seed=1, verb_time=0)
(3_w,7)-CMA-ES (mu_w=2.3,w_1=58%) in dimension 3 (seed=1)
Covariance matrix is diagonal for 2 iterations (1/ccov=7.0)
Iterat #Fevals function value axis ratio sigma minstd maxstd min:sec
1 7 1.453161670768570e+04 1.2e+00 1.08e+00 1e+00 1e+00
2 14 3.281197961927601e+04 1.3e+00 1.22e+00 1e+00 2e+00
3 21 1.082851071704020e+04 1.3e+00 1.24e+00 1e+00 2e+00
100 700 8.544042012075362e+00 1.4e+02 3.18e-01 1e-03 2e-01
200 1400 5.691152415221861e-12 1.0e+03 3.82e-05 1e-09 1e-06
220 1540 3.890107746209078e-15 9.5e+02 4.56e-06 8e-11 7e-08
termination on tolfun : 1e-11
final/bestever f-value = 3.89010774621e-15 2.52273602735e-15
mean solution: [ -4.63614606e-08 -3.42761465e-10 1.59957987e-11]
std deviation: [ 6.96066282e-08 2.28704425e-09 7.63875911e-11]
Test on the Rosenbrock function with 3 restarts. The first trial only
finds the local optimum, which happens in about 20% of the cases.
>>> import cma
>>> res = cma.fmin(cma.fcts.rosen, 4*[-1],1, ftarget=1e-6, restarts=3, verb_time=0, verb_disp=500, seed=3)
(4_w,8)-CMA-ES (mu_w=2.6,w_1=52%) in dimension 4 (seed=3)
Iterat #Fevals function value axis ratio sigma minstd maxstd min:sec
1 8 4.875315645656848e+01 1.0e+00 8.43e-01 8e-01 8e-01
2 16 1.662319948123120e+02 1.1e+00 7.67e-01 7e-01 8e-01
3 24 6.747063604799602e+01 1.2e+00 7.08e-01 6e-01 7e-01
184 1472 3.701428610430019e+00 4.3e+01 9.41e-07 3e-08 5e-08
termination on tolfun : 1e-11
final/bestever f-value = 3.70142861043 3.70142861043
mean solution: [-0.77565922 0.61309336 0.38206284 0.14597202]
std deviation: [ 2.54211502e-08 3.88803698e-08 4.74481641e-08 3.64398108e-08]
(8_w,16)-CMA-ES (mu_w=4.8,w_1=32%) in dimension 4 (seed=4)
Iterat #Fevals function value axis ratio sigma minstd maxstd min:sec
1 1489 2.011376859371495e+02 1.0e+00 8.90e-01 8e-01 9e-01
2 1505 4.157106647905128e+01 1.1e+00 8.02e-01 7e-01 7e-01
3 1521 3.548184889359060e+01 1.1e+00 1.02e+00 8e-01 1e+00
111 3249 6.831867555502181e-07 5.1e+01 2.62e-02 2e-04 2e-03
termination on ftarget : 1e-06
final/bestever f-value = 6.8318675555e-07 1.18576673231e-07
mean solution: [ 0.99997004 0.99993938 0.99984868 0.99969505]
std deviation: [ 0.00018973 0.00038006 0.00076479 0.00151402]
>>> assert res[1] <= 1e-6
Notice the different termination conditions. Termination on the target
function value ftarget prevents further restarts.
Test of scaling_of_variables option
>>> import cma
>>> opts = cma.Options()
>>> opts['seed'] = 456
>>> opts['verb_disp'] = 0
>>> opts['CMA_active'] = 1
>>> # rescaling of third variable: for searching in roughly
>>> # x0 plus/minus 1e3*sigma0 (instead of plus/minus sigma0)
>>> opts.scaling_of_variables = [1, 1, 1e3, 1]
>>> res = cma.fmin(cma.fcts.rosen, 4 * [0.1], 0.1, **opts)
termination on tolfun : 1e-11
final/bestever f-value = 2.68096173031e-14 1.09714829146e-14
mean solution: [ 1.00000001 1.00000002 1.00000004 1.00000007]
std deviation: [ 3.00466854e-08 5.88400826e-08 1.18482371e-07 2.34837383e-07]
The printed std deviations reflect the actual true value (not the one
in the internal representation which would be different).
:See: cma.main(), cma._test()
Data Fcts = <cma.FitnessFunctions object>
__docformat__ = 'reStructuredText'
__version__ = '0.91.00 $Revision: 3103 $'
division = _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
exp = <ufunc 'exp'>
fcts = <cma.FitnessFunctions object>
inf = inf
log = <ufunc 'log'>
rotate = <cma.Rotation object>
show = <matplotlib.backends.backend_tkagg.Show object>
sqrt = <ufunc 'sqrt'>
use_sent_solutions = True
with_statement = _Feature((2, 5, 0, 'alpha', 1), (2, 6, 0, 'alpha', 0), 32768)
- CMA-ES 和python
- Python的CMA-ES扩展1.0版本文档
- CMA-ES算法解决连续优化问题
- cma
- CMA
- CMA
- Linux Kernel 内存管理之CMA分配和释放
- CMA Introduce
- Linux CMA
- 私有cma
- CMA debug
- hermes和solr、es
- EGLSurfaces 和 OpenGL ES
- 并发和OpenGL ES
- ES集群和分片
- ES架构和使用方法
- 北大CMA课程一次搞定CMA认证
- CMA计量认证简介
- Android Activity 四种启动模式 总结
- MySQL数据库引擎ISAM MyISAM HEAP InnoDB的区别
- 绑定ListView
- Linux 原子操作
- javascript定义函数的三种方法
- CMA-ES 和python
- Printf格式输出
- 如何让你用ps制作非常炫耀的网站导航按钮
- Android Animation
- 功能:插入耳机,提示打开与耳机相关的app
- 获取CxDBTreeList所有父节点
- windows服务安装卸载,sharepointWSP安装卸载
- 模板 树状数组
- 蓝桥杯:打印十字图