PySwarms

raw JSON →
1.3.0 verified Fri May 01 auth: no python maintenance

PySwarms is a Python library for Particle Swarm Optimization (PSO). It provides a simple and intuitive API for implementing PSO algorithms, including global best (gbest), local best (lbest), and binary PSO, as well as tools for visualization and hyperparameter tuning. The current version is 1.3.0, released in 2021. The project is in maintenance mode with quarterly release cadence.

pip install pyswarms
error AttributeError: module 'pyswarms' has no attribute 'GlobalBestPSO'
cause Trying to import optimizer from top-level pyswarms.
fix
Use: from pyswarms.single import GlobalBestPSO
error ValueError: operands could not be broadcast together with shapes (10,2) (2,)
cause Objective function returns wrong shape (e.g., returns a single value for all particles).
fix
Ensure objective function returns an array of shape (n_particles,), i.e., one cost per particle.
error KeyError: 'c1'
cause Missing required key in options dict for optimizer.
fix
Provide options as dict: {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
error TypeError: 'NoneType' object is not callable
cause Using the old animate module incorrectly or passing None as a callback.
fix
Use the new plotters API: from pyswarms.utils.plotters import plot_cost_history
deprecated The 'animate' module and some plotting functions have been deprecated in favor of plotters. Check documentation for the correct API.
fix Use pyswarms.utils.plotters instead of pyswarms.utils.animate.
gotcha The optimizer modifies the objective function's arguments; ensure the function signature is correct (returns array of shape (n_particles,)). Mistakes lead to shape errors.
fix Your objective function must accept a 2D array (rows=particles, cols=dimensions) and return a 1D array of costs.
gotcha Always pass options as a dict with keys 'c1', 'c2', 'w' for PSO variants. Missing keys cause KeyError or unexpected behavior.
fix options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
breaking Version 1.0.0 changed the backend API and removed many old functions. Code written for v0.x may not work.
fix Review migration guide: https://pyswarms.readthedocs.io/en/latest/migration.html

Minimal example optimizing the sphere function with global best PSO.

import numpy as np
from pyswarms.single import GlobalBestPSO

def sphere(x):
    return np.sum(x**2, axis=1)

optimizer = GlobalBestPSO(n_particles=10, dimensions=2, options={'c1': 0.5, 'c2': 0.3, 'w':0.9})
cost, pos = optimizer.optimize(sphere, iters=100)
print("Best cost:", cost)
print("Best position:", pos)