pyswarms.swarms package¶
This package contains the Swarm class for creating your own swarm implementation. The class acts as a DataClass, holding information on the particles you have generated throughout each timestep. It offers a pre-built and flexible way of building your own swarm.
pyswarms.swarms class¶
-
class
pyswarms.backend.swarms.
Swarm
(position: numpy.ndarray, velocity: numpy.ndarray, n_particles: int = NOTHING, dimensions: int = NOTHING, options: dict = {}, pbest_pos: numpy.ndarray = NOTHING, best_pos: numpy.ndarray = array([], dtype=float64), pbest_cost: numpy.ndarray = array([], dtype=float64), best_cost: float = inf, current_cost: numpy.ndarray = array([], dtype=float64))[source]¶ A Swarm Class
This class offers a generic swarm that can be used in most use-cases such as single-objective optimization, etc. It contains various attributes that are commonly-used in most swarm implementations.
To initialize this class, simply supply values for the position and velocity matrix. The other attributes are automatically filled. If you want to initialize random values, take a look at:
pyswarms.backend.generators.generate_swarm()
: for generating positions randomly.pyswarms.backend.generators.generate_velocity()
: for generating velocities randomly.
If your swarm requires additional parameters (say c1, c2, and w in gbest PSO), simply pass them to the
options
dictionary.As an example, say we want to create a swarm by generating particles randomly. We can use the helper methods above to do our job:
import pyswarms.backend as P from pyswarms.backend.swarms import Swarm # Let's generate a 10-particle swarm with 10 dimensions init_positions = P.generate_swarm(n_particles=10, dimensions=10) init_velocities = P.generate_velocity(n_particles=10, dimensions=10) # Say, particle behavior is governed by parameters `foo` and `bar` my_options = {'foo': 0.4, 'bar': 0.6} # Initialize the swarm my_swarm = Swarm(position=init_positions, velocity=init_velocities, options=my_options)
From there, you can now use all the methods in
pyswarms.backend
. Of course, the process above has been abstracted by the methodpyswarms.backend.generators.create_swarm()
so you don’t have to write the whole thing down.-
position
¶ position-matrix at a given timestep of shape
(n_particles, dimensions)
Type: numpy.ndarray
-
velocity
¶ velocity-matrix at a given timestep of shape
(n_particles, dimensions)
Type: numpy.ndarray
-
pbest_pos
¶ personal best positions of each particle of shape
(n_particles, dimensions)
Default is NoneType: numpy.ndarray
-
best_pos
¶ best position found by the swarm of shape
(dimensions, )
for thepyswarms.backend.topology.Star
topology and(dimensions, particles)
for the other topologiesType: numpy.ndarray
-
pbest_cost
¶ personal best costs of each particle of shape
(n_particles, )
Type: numpy.ndarray
-
current_cost
¶ the current cost found by the swarm of shape
(n_particles, dimensions)
Type: numpy.ndarray