pyswarms.base package¶
The pyswarms.base
module implements base
swarm classes to implement variants of particle swarm optimization.
pyswarms.base module¶
Base class for single-objective Particle Swarm Optimization implementations.
All methods here are abstract and raise a NotImplementedError
when not used. When defining your own swarm implementation,
create another class,
>>> class MySwarm(SwarmBase):
>>> def __init__(self):
>>> super(MySwarm, self).__init__()
and define all the necessary methods needed.
As a guide, check the global best and local best implementations in this package.
Note
Regarding options
, it is highly recommended to
include parameters used in position and velocity updates as
keyword arguments. For parameters that affect the topology of
the swarm, it may be much better to have them as positional
arguments.
See also
pyswarms.single.global_best
global-best PSO implementation
pyswarms.single.local_best
local-best PSO implementation
pyswarms.single.general_optimizer
a more general PSO implementation with a custom topology
-
class
pyswarms.base.base_single.
SwarmOptimizer
(n_particles, dimensions, options, bounds=None, velocity_clamp=None, center=1.0, ftol=-inf, ftol_iter=1, init_pos=None)[source]¶ Bases:
abc.ABC
-
__init__
(n_particles, dimensions, options, bounds=None, velocity_clamp=None, center=1.0, ftol=-inf, ftol_iter=1, init_pos=None)[source]¶ Initialize the swarm
Creates a Swarm class depending on the values initialized
-
n_particles
¶ number of particles in the swarm.
- Type
int
-
dimensions
¶ number of dimensions in the space.
- Type
int
-
options
¶ a dictionary containing the parameters for the specific optimization technique
- c1float
cognitive parameter
- c2float
social parameter
- wfloat
inertia parameter
- Type
dict with keys
{'c1', 'c2', 'w'}
-
bounds
¶ a tuple of size 2 where the first entry is the minimum bound while the second entry is the maximum bound. Each array must be of shape
(dimensions,)
.- Type
tuple of numpy.ndarray, optional
-
velocity_clamp
¶ a tuple of size 2 where the first entry is the minimum velocity and the second entry is the maximum velocity. It sets the limits for velocity clamping.
- Type
tuple, optional
-
center
¶ an array of size
dimensions
- Type
list, optional
-
ftol
¶ relative error in objective_func(best_pos) acceptable for convergence. Default is
-np.inf
.- Type
float, optional
-
ftol_iter
¶ number of iterations over which the relative error in objective_func(best_pos) is acceptable for convergence. Default is
1
- Type
int
-
-
_abc_impl
= <_abc_data object>¶
-
_populate_history
(hist)[source]¶ Populate all history lists
The
cost_history
,mean_pbest_history
, andneighborhood_best
is expected to have a shape of(iters,)
,on the other hand, thepos_history
andvelocity_history
are expected to have a shape of(iters, n_particles, dimensions)
- Parameters
hist (collections.namedtuple) – Must be of the same type as self.ToHistory
-
abstract
optimize
(objective_func, iters, n_processes=None, **kwargs)[source]¶ Optimize the swarm for a number of iterations
Performs the optimization to evaluate the objective function
objective_func
for a number of iterationsiter.
- Parameters
objective_func (function) – objective function to be evaluated
iters (int) – number of iterations
n_processes (int) – number of processes to use for parallel particle evaluation Default is None with no parallelization
kwargs (dict) – arguments for objective function
- Raises
NotImplementedError – When this method is not implemented.
-
reset
()[source]¶ Reset the attributes of the optimizer
All variables/atributes that will be re-initialized when this method is defined here. Note that this method can be called twice: (1) during initialization, and (2) when this is called from an instance.
It is good practice to keep the number of resettable attributes at a minimum. This is to prevent spamming the same object instance with various swarm definitions.
Normally, swarm definitions are as atomic as possible, where each type of swarm is contained in its own instance. Thus, the following attributes are the only ones recommended to be resettable:
Swarm position matrix (self.pos)
Velocity matrix (self.pos)
Best scores and positions (gbest_cost, gbest_pos, etc.)
Otherwise, consider using positional arguments.
-
Base class for single-objective discrete Particle Swarm Optimization implementations.
All methods here are abstract and raises a NotImplementedError
when not used. When defining your own swarm implementation,
create another class,
>>> class MySwarm(DiscreteSwarmOptimizer):
>>> def __init__(self):
>>> super(MySwarm, self).__init__()
and define all the necessary methods needed.
As a guide, check the discrete PSO implementations in this package.
Note
Regarding options
, it is highly recommended to
include parameters used in position and velocity updates as
keyword arguments. For parameters that affect the topology of
the swarm, it may be much better to have them as positional
arguments.
See also
pyswarms.discrete.binary
binary PSO implementation
-
class
pyswarms.base.base_discrete.
DiscreteSwarmOptimizer
(n_particles, dimensions, binary, options, velocity_clamp=None, init_pos=None, ftol=-inf, ftol_iter=1)[source]¶ Bases:
abc.ABC
-
__init__
(n_particles, dimensions, binary, options, velocity_clamp=None, init_pos=None, ftol=-inf, ftol_iter=1)[source]¶ Initialize the swarm.
Creates a
numpy.ndarray
of positions depending on the number of particles needed and the number of dimensions. The initial positions of the particles depends on the argumentbinary
, which governs if a binary matrix will be produced.-
n_particles
¶ number of particles in the swarm.
- Type
int
-
dimensions
¶ number of dimensions in the space.
- Type
int
-
binary
¶ a trigger to generate a binary matrix for the swarm’s initial positions. When passed with a
False
value, random integers from 0 todimensions
are generated.- Type
boolean
-
options
¶ a dictionary containing the parameters for the specific optimization technique
- c1float
cognitive parameter
- c2float
social parameter
- wfloat
inertia parameter
- Type
dict with keys
{'c1', 'c2', 'w'}
-
velocity_clamp
¶ a tuple of size 2 where the first entry is the minimum velocity and the second entry is the maximum velocity. It sets the limits for velocity clamping.
- Type
tuple, optional
-
ftol
¶ relative error in objective_func(best_pos) acceptable for convergence. Default is
-np.inf
.- Type
float, optional
-
ftol_iter
¶ number of iterations over which the relative error in objective_func(best_pos) is acceptable for convergence. Default is
1
- Type
int
-
options
a dictionary containing the parameters for a specific optimization technique
- Type
dict
-
-
_abc_impl
= <_abc_data object>¶
-
_populate_history
(hist)[source]¶ Populate all history lists
The
cost_history
,mean_pbest_history
, andneighborhood_best
is expected to have a shape of(iters,)
,on the other hand, thepos_history
andvelocity_history
are expected to have a shape of(iters, n_particles, dimensions)
- Parameters
hist (collections.namedtuple) – Must be of the same type as self.ToHistory
-
abstract
optimize
(objective_func, iters, n_processes=None, **kwargs)[source]¶ Optimize the swarm for a number of iterations
Performs the optimization to evaluate the objective function
objective_func
for a number of iterationsiter.
- Parameters
objective_func (callable) – objective function to be evaluated
iters (int) – number of iterations
n_processes (int) – number of processes to use for parallel particle evaluation Default is None with no parallelization
kwargs (dict) – arguments for objective function
- Raises
NotImplementedError – When this method is not implemented.
-
reset
()[source]¶ Reset the attributes of the optimizer
All variables/atributes that will be re-initialized when this method is defined here. Note that this method can be called twice: (1) during initialization, and (2) when this is called from an instance.
It is good practice to keep the number of resettable attributes at a minimum. This is to prevent spamming the same object instance with various swarm definitions.
Normally, swarm definitions are as atomic as possible, where each type of swarm is contained in its own instance. Thus, the following attributes are the only ones recommended to be resettable:
Swarm position matrix (self.pos)
Velocity matrix (self.pos)
Best scores and positions (gbest_cost, gbest_pos, etc.)
Otherwise, consider using positional arguments.
-