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:

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 method pyswarms.backend.generators.create_swarm() so you don’t have to write the whole thing down.


numpy.ndarray – position-matrix at a given timestep of shape (n_particles, dimensions)


numpy.ndarray – velocity-matrix at a given timestep of shape (n_particles, dimensions)


int – number of particles in a swarm.


int – number of dimensions in a swarm.


dict – various options that govern a swarm’s behavior.


numpy.ndarray – personal best positions of each particle of shape (n_particles, dimensions) Default is None


numpy.ndarray – best position found by the swarm of shape (dimensions, ) for the pyswarms.backend.topology.Star topology and (dimensions, particles) for the other topologies


numpy.ndarray – personal best costs of each particle of shape (n_particles, )


float – best cost found by the swarm, default is numpy.inf


numpy.ndarray – the current cost found by the swarm of shape (n_particles, dimensions)