Skip to content

Blog Post

An Optimization Example Using the Particle Swarm Optimization Algorithm

A hands-on introduction to particle swarm optimization: inertia, memory and swarm terms explained with geometry, applied to a constrained problem with real convergence data.

Algorithms

This article is the companion of An Optimization Example Using the Differential Evolution Algorithm. It takes exactly the same problem (the same objective, the same constraint, the same penalty, the same budget of function evaluations) and solves it with another famous metaheuristic, particle swarm optimization (PSO). The goal is twofold: to explain every step of the algorithm in a clear and simple way, with a practical example, code and results, and to see, on equal terms, how the two methods behave. As we shall see, they have rather different personalities.

Introduction to Particle Swarm Optimization

Particle Swarm Optimization (PSO) is a population-based, stochastic optimizer introduced by James Kennedy and Russell Eberhart in 1995. It was inspired by the collective movement of bird flocks and fish schools. Like differential evolution it minimizes a real-valued objective function over a continuous search space and needs no derivatives: it only ever evaluates the objective, which makes it a natural choice for black-box problems.

The method is popular because it is simple (the core is a few dozen lines of code), has only a few control parameters (the swarm size $N$, the inertia weight $w$ and the two acceleration coefficients $c_1$ and $c_2$) and finds a good region of the search space remarkably fast. In return, the basic algorithm gives no mathematical guarantee of reaching the global optimum, may converge prematurely, and, as in every metaheuristic, constraints need explicit handling. For a smooth, convex problem a gradient-based method is far cheaper.

The key idea. A swarm of particles flies through the search space. Every particle keeps part of its previous motion (inertia) and is pulled towards two places: the best point it has found itself (its memory) and the best point the whole swarm has found so far (the social information). Exploration is controlled by the balance of these three influences, and the swarm gradually contracts around a good solution.
Problem statement. Given an objective $f:\mathbb{R}^D \to \mathbb{R}$, bounds $L_j \le x_j \le U_j$ and, optionally, constraints $g_k(\mathbf{x}) \le 0$, find $$\mathbf{x}^{*} = \arg\min_{\mathbf{x}} f(\mathbf{x}) \quad \text{subject to} \quad g_k(\mathbf{x}) \le 0,\; k = 1,\dots,K.$$

Algorithm Overview

PSO maintains a swarm of $N$ particles. Each particle $i$ has a position $\mathbf{x}_i\in\mathbb{R}^D$ (a candidate solution), a velocity $\mathbf{v}_i\in\mathbb{R}^D$ and a memory: its personal best position $\mathbf{p}_i$, the best point it has visited so far. The swarm as a whole remembers the global best position $\mathbf{g}$. In every iteration $t$ the swarm evaluates the objective, updates the bests, accelerates every particle towards them, and moves it.

1 Initialize N particles random x and v 2 Evaluate update pi and g remember the bests 3 Accelerate v = w·v + c1r1(p − x) + c2r2(g − x) 4 Move x = x + v then clip to bounds repeat for t = 1 … Tmax, or until the swarm has converged
Fig. 1 – One iteration of particle swarm optimization. After the random initialization, every iteration evaluates the swarm, updates the personal and global bests, computes new velocities and moves the particles.
1
Initialization – sample $N$ positions uniformly inside the bounds, give each particle a small random velocity and evaluate the swarm.
2
Evaluation – update each personal best $\mathbf{p}_i$ if the new position is better, then update the global best $\mathbf{g}$.
3
Velocity update – combine the old velocity with the pulls towards $\mathbf{p}_i$ and $\mathbf{g}$.
4
Move – add the velocity to the position and bring any particle that left the search box back to its boundary.
5
Repeat steps 2–4 until $T_{\max}$ iterations have run, or the swarm has converged.

Control Parameters

ParameterMeaningUsual rangeEffect
$N$Swarm size$20$ to $50$ for small problemsLarger: more diversity and robustness, more evaluations per iteration
$w$Inertia weight$0.4$ to $0.9$ (or $0.7298$, see below)Larger: particles keep moving and explore; smaller: they settle quickly
$c_1$Cognitive coefficient (memory)$1.5$ to $2$Larger: stronger pull towards the particle's own best position
$c_2$Social coefficient (swarm)$1.5$ to $2$Larger: stronger pull towards the best position of the swarm
$T_{\max}$Number of iterationsproblem dependentSets the evaluation budget, $N \cdot T_{\max}$

The ranges are common rules of thumb from the PSO literature, not guarantees. The parameter study below shows how sensitive the outcome can be, even on a two-dimensional problem.

Step 1 – Initialization

The initial positions are drawn uniformly at random from the search box, so that the swarm covers the whole domain, and the velocities are small random numbers (here within ±10 % of the box width):

$$x_{i,j,0} = L_j + \text{rand}_{[0,1]} \cdot (U_j - L_j), \qquad v_{i,j,0} = 0.2\,\bigl(\text{rand}_{[0,1]} - 0.5\bigr)(U_j - L_j)$$

Each particle starts with $\mathbf{p}_i = \mathbf{x}_i$, and the best of them becomes the global best $\mathbf{g}$. A fixed random seed makes a run reproducible, which matters when you compare parameter settings.

Step 2 – The Velocity Update

This single line is the heart of PSO. In every iteration each particle's new velocity is the sum of three terms:

$$\mathbf{v}_i \;\leftarrow\; \underbrace{w\,\mathbf{v}_i}_{\text{inertia}} \;+\; \underbrace{c_1\,\mathbf{r}_1 \odot (\mathbf{p}_i - \mathbf{x}_i)}_{\text{memory (cognitive)}} \;+\; \underbrace{c_2\,\mathbf{r}_2 \odot (\mathbf{g} - \mathbf{x}_i)}_{\text{swarm (social)}}$$

Here $\mathbf{r}_1$ and $\mathbf{r}_2$ are vectors of fresh uniform random numbers in $[0,1]$, one per coordinate, and $\odot$ is the component-wise product. The three terms have a simple physical meaning:

  • Inertia $w\mathbf{v}_i$ is the momentum: the particle tends to continue in the direction in which it was already travelling. It prevents abrupt turns and carries particles across the search space.
  • Memory $c_1\mathbf{r}_1\odot(\mathbf{p}_i-\mathbf{x}_i)$ points from the particle to the best place it has ever found itself. It lets every particle explore on its own.
  • Swarm $c_2\mathbf{r}_2\odot(\mathbf{g}-\mathbf{x}_i)$ points from the particle to the best place found by anyone. It shares information and makes the swarm converge.

Because of the random factors, the pull is not a fixed vector: it can be anywhere in the rectangle spanned by the particle and the target, scaled by $c$ (Fig. 2). On average $r = 0.5$, so the average pull of each term is $c/2$ of the distance to its target.

0 2 4 6 8 10 2 4 6 8 x1 x2 p g xi (particle) xnew previous v inertia w·v memory c₁r₁(p − x) swarm c₂r₂(g − x) new velocity
Fig. 2 – The velocity update in two dimensions (to scale). The particle $\mathbf{x}_i$ has the previous velocity $(1.2,\,0.5)$; its personal best is $\mathbf{p}$ and the swarm's best is $\mathbf{g}$. With $w = 0.7298$, $c_1=c_2=1.49618$, $\mathbf{r}_1=(0.5,\,0.3)$ and $\mathbf{r}_2=(0.2,\,0.35)$ the three terms (purple, green, orange) add up to the new velocity $(2.70,\,3.73)$ (black), which carries the particle to $\mathbf{x}^{new}$. The dashed rectangles show where the memory and swarm terms could have ended up for other values of $\mathbf{r}_1$ and $\mathbf{r}_2$.

Choosing $w$, $c_1$ and $c_2$: the constriction coefficients

With $w=1$ and large $c$ the velocities can grow without limit and the swarm “explodes”. Two classical remedies are an inertia weight $w<1$ (Shi and Eberhart, 1998) and the constriction analysis of Clerc and Kennedy (2002). For $c_1+c_2=\varphi=4.1$ their constriction factor is $\chi = 2/\bigl|2-\varphi-\sqrt{\varphi^2-4\varphi}\bigr| \approx 0.7298$, which corresponds to $w = 0.7298$ and $c_1=c_2=2.05\chi \approx 1.49618$. This is the setting we use as the baseline: it is stable, and a good default for many problems.

Step 3 – Moving and Staying in the Box

The particle simply moves by its new velocity:

$$\mathbf{x}_i \;\leftarrow\; \mathbf{x}_i + \mathbf{v}_i.$$

A particle may fly out of the search box. In our implementation such a coordinate is clipped to the nearest bound and the corresponding velocity component is set to zero, so that the particle stops at the wall instead of pushing against it again and again. Other common remedies are to reflect the particle back into the box, to let it leave and not evaluate it, or to restrict the speed with a maximum velocity $v_{\max}$ (often a fraction of the box width).

Step 4 – Updating the Bests and the Neighbourhood

After the move, the swarm is evaluated. A particle replaces its personal best if the new position is better:

$$\mathbf{p}_{i} \leftarrow \mathbf{x}_{i} \;\text{ if } f(\mathbf{x}_{i}) < f(\mathbf{p}_{i}), \qquad \mathbf{g} \leftarrow \arg\min_{i} f(\mathbf{p}_{i}).$$

The global best can therefore never get worse (it is elitist), but, unlike in differential evolution, the particles themselves are not replaced by better ones: a particle keeps moving even when its new position is worse than the old one, which is what allows it to overshoot, escape and explore. In our implementation the update is synchronous: all particles are moved and evaluated first, and the bests are updated afterwards.

Who is a particle's neighbour?

So far the social term used the best position of the whole swarm (gbest PSO). The alternative is to let every particle see only a small neighbourhood, for instance its two neighbours on a ring (lbest PSO, Fig. 3). Information then travels slowly around the ring, which keeps the swarm diverse for longer.

Global best (gbest) every particle sees the whole swarm orange: the particle; green: its neighbours Ring (lbest, k = 2) each particle sees only two neighbours orange: the particle; green: its neighbours
Fig. 3 – Two neighbourhood topologies. In the global-best topology the social pull points to the best particle of the whole swarm; in the ring topology only to the best among the particle itself and its two neighbours.
TopologyInformation flowCharacter
Global best (gbest)Immediate: every particle follows the best of the swarmFast convergence, higher risk of premature convergence
Ring (lbest)Slow: through overlapping neighbourhoodsSlower, but explores more and is better on multimodal problems

This article uses the global-best topology, the simplest and fastest one.

Handling Constraints with a Penalty

Like differential evolution, PSO knows nothing about constraints. We use the same exterior penalty as in the previous article: add to the objective a term that is zero for feasible points and grows with the amount of violation,

$$\tilde{f}(\mathbf{x}) = f(\mathbf{x}) + \rho \sum_{k=1}^{K} \max\bigl(0,\, g_k(\mathbf{x})\bigr).$$

The swarm then minimizes $\tilde{f}$ as if it were an ordinary unconstrained function. For this absolute-value penalty, the penalty is exact (its minimizer coincides with the constrained minimizer) as soon as $\rho$ is larger than the Lagrange multiplier $\lambda$ of the active constraint. We compute $\lambda$ in the worked example. A much larger $\rho$ than necessary is not free either, because it turns the boundary into a steep cliff. This matters particularly for PSO, because particles overshoot: a particle that flies across the boundary lands on the cliff and pays dearly for it.

Alternatives. Deb's feasibility rules (a feasible point beats an infeasible one; two infeasible points are ranked by violation) need no penalty weight and work well with PSO when they are used to decide the personal and global bests. Other approaches repair infeasible particles by projecting them back onto the feasible region. We use the penalty here because it is easy to see and easy to code, and because it keeps the comparison with differential evolution fair.

Worked Example – The Same Constrained Two-Variable Problem

We minimize the squared distance to the point $(2,3)$ while staying on one side of a line:

$$\begin{aligned}\min_{x,y}\;& f(x,y) = (x-2)^2 + (y-3)^2 \\ \text{subject to}\;& g(x,y) = x + y - 4 \le 0, \quad 0 \le x,y \le 10.\end{aligned}$$

The unconstrained minimum $(2,3)$ has $x+y=5$, so it violates the constraint: the constraint is active and the solution must lie on the line $x+y=4$.

The Exact Answer, for Reference

At the constrained minimum the gradient of $f$ must be a multiple of the gradient of the active constraint, $\bigl(2(x-2),\, 2(y-3)\bigr) = -\lambda\,(1,\,1)$ with $x + y = 4$. It follows that $y = x + 1$, hence $x^*=1.5$, $y^*=2.5$, $\lambda = 1 > 0$ and $f^* = 0.5$. Geometrically, the optimum is the point of the line closest to $(2,3)$, where the contour $f=0.5$ just touches the constraint line (Fig. 4). Since $\lambda = 1$, any penalty weight $\rho > 1$ is exact; as before we use $\rho = 100$.

0 2 4 6 8 0 2 4 6 8 x y f = 2 f = 5 f = 10 f = 20 feasible region infeasible region: x + y > 4 x + y = 4 unconstrained minimum (2, 3), f = 0 constrained optimum (1.5, 2.5), f = 0.5
Fig. 4 – The problem. Blue circles are contours of $f$, the red line is the constraint $x+y=4$ and the shaded red half-plane is infeasible. The unconstrained minimum $(2,3)$ is infeasible; the constrained optimum $(1.5,\,2.5)$ is where the contour $f=0.5$ touches the line.

Python Implementation

The listing below is complete and was run to produce every number and figure in this article. The problem, the penalty and the budget are the same as in the differential evolution article: a swarm of $N=20$ particles and 200 iterations need $N\cdot T_{\max} + N = 4020$ objective evaluations, exactly as many as DE with $NP=20$ and 200 generations. The update is synchronous, and the history of the swarm is stored for plotting.

import numpy as np

# ---- problem (the same as in the differential evolution article) ---
def objective(p):
    x, y = p
    return (x - 2) ** 2 + (y - 3) ** 2

def violation(p):
    """Amount by which g(x, y) = x + y - 4 <= 0 is violated."""
    x, y = p
    return max(0.0, x + y - 4)

RHO = 100.0

def penalized(p):
    return objective(p) + RHO * violation(p)

# ---- particle swarm optimization (global-best PSO) -----------------
def particle_swarm(func, bounds, n_particles=20, w=0.7298, c1=1.49618, c2=1.49618,
                   n_iter=200, seed=42):
    rng = np.random.default_rng(seed)
    lo, hi = np.array(bounds, dtype=float).T
    D = len(lo)

    x = lo + rng.random((n_particles, D)) * (hi - lo)          # positions
    v = (rng.random((n_particles, D)) - 0.5) * (hi - lo) * 0.2  # velocities
    fx = np.array([func(p) for p in x])

    pbest, pbest_f = x.copy(), fx.copy()                       # each particle's own best
    g = np.argmin(pbest_f)
    gbest, gbest_f = pbest[g].copy(), pbest_f[g]               # the swarm's best

    history = [(x.copy(), v.copy(), gbest.copy(), gbest_f, pbest_f.copy())]
    for _ in range(n_iter):
        r1 = rng.random((n_particles, D))
        r2 = rng.random((n_particles, D))
        # velocity update: inertia + pull to own best + pull to swarm best
        v = w * v + c1 * r1 * (pbest - x) + c2 * r2 * (gbest - x)
        x = x + v                                              # move

        out = (x < lo) | (x > hi)                              # boundaries: clip, and stop there
        x = np.clip(x, lo, hi)
        v[out] = 0.0

        fx = np.array([func(p) for p in x])
        better = fx < pbest_f                                  # update personal bests
        pbest[better], pbest_f[better] = x[better], fx[better]
        g = np.argmin(pbest_f)
        if pbest_f[g] < gbest_f:                               # update the global best
            gbest, gbest_f = pbest[g].copy(), pbest_f[g]

        history.append((x.copy(), v.copy(), gbest.copy(), gbest_f, pbest_f.copy()))
    return gbest, gbest_f, history


bounds = [(0, 10), (0, 10)]
best, f_best, history = particle_swarm(penalized, bounds, n_particles=20,
                                       w=0.7298, c1=1.49618, c2=1.49618,
                                       n_iter=200, seed=42)

print(f"best x = {best[0]:.6f}, y = {best[1]:.6f}")
print(f"f(x, y) = {objective(best):.8f},  x + y = {best.sum():.6f}")

Running the driver gives

best x = 1.496518, y = 2.503482
f(x, y) = 0.50002435,  x + y = 4.000000

The swarm has found the optimum to about four decimals: $(1.4965,\,2.5035)$ against the exact $(1.5,\,2.5)$, a final error of $2.4\cdot10^{-5}$ in the objective. That is a good answer for an engineering purpose, but noticeably coarser than the six decimals that differential evolution reached with the same number of evaluations. The reasons are discussed in the comparison below.

Watching the Swarm Converge

Fig. 5 shows the 20 particles at four moments of the run with seed 42; the grey arrows are their velocities. At iteration 0 the swarm is scattered over the whole box and none of the particles is feasible, so the best one (orange) is simply the one that violates the constraint least. Within three iterations the particles, pulled towards the good region, have flown to the lower left corner and 16 of the 20 are feasible. Note the long velocity arrows: this is the momentum of the swarm. By iteration 10 the swarm is gathering around the optimum, but it is still moving fast and the particles overshoot the constraint line, so that only 9 of 20 are feasible. By iteration 30 it has contracted around the optimum on the line $x+y=4$.

This picture also shows a difference from differential evolution. In DE a particle is only replaced by a better trial, so the population ends up feasible (20 of 20 at generation 30). The PSO particles keep moving after they have found something good, and since the optimum lies on the boundary, they keep crossing it: at iteration 30, 14 of the 20 are feasible. What matters is that the global best (orange) is feasible from iteration 1 on, and it always remains so.

0 5 10 0 5 10 x y t = 0 0/20 feasible 0 2 4 6 0 2 4 6 x y t = 3 16/20 feasible 0 1 2 3 4 5 0 1 2 3 4 5 x y t = 10 9/20 feasible 0.5 1 1.5 2 2.5 1 1.5 2 2.5 x y t = 30 14/20 feasible feasible infeasible global best g optimum (1.5, 2.5) velocity
Fig. 5 – Swarm snapshots (seed 42, $N=20$). Green points are feasible, red points infeasible, grey arrows show each particle's velocity. The panels use different axis ranges so that the late stages remain visible. The black dot marks the true optimum $(1.5, 2.5)$.

Convergence History

The table lists the global best of the same run (error $=\tilde f - f^*$ with $f^*=0.5$).

IterationBest f̃xyx+yError f̃ − f*
0124.2024304.66720.43805.10521.2 × 102
15.3153252.41510.73223.14734.8 × 100
50.6429931.57982.31703.89691.4 × 10−1
100.5352171.44422.52433.96853.5 × 10−2
300.5008001.49142.50793.99938.0 × 10−4
500.5006291.49502.50443.99946.3 × 10−4
1000.5000311.49652.50354.00003.1 × 10−5
1500.5000251.49652.50354.00002.5 × 10−5
2000.5000241.49652.50354.00002.4 × 10−5

The best particle gets very close to the optimum within 10 iterations (error $3.5\cdot10^{-2}$) and within 30 iterations the error is below $10^{-3}$. After that, progress slows down considerably: the last digits take a long time, and after iteration 100 the error hardly changes.

Convergence Plot

On a logarithmic axis the curve falls steeply during the first 10 to 30 iterations and then flattens out, in contrast to the almost straight line of differential evolution. The stairs of the curve of the global best are characteristic of PSO as well: it improves only in bursts, whenever some particle finds a better position. The mean of the personal bests (orange) lags behind. The thirty grey curves come from independent runs with seeds 0–29; all of them reached an error below $10^{-3}$, and 25 of them below $10^{-4}$. After 200 iterations the final errors are between $2\cdot10^{-8}$ and $2.4\cdot10^{-4}$ (median $2.5\cdot10^{-5}$), so the behaviour is not a lucky seed.

0 25 50 75 100 125 150 175 200 10−8 10−7 10−6 10−5 10−4 10−3 10−2 10−1 100 101 102 103 Iteration t Best fitness error f̃ − f* global best (seed 42) mean personal best (seed 42) 30 independent runs (seeds 0–29) Values below 10−8 are drawn at the floor of the axis.
Fig. 6 – Convergence of the best penalized fitness. Error relative to the known optimum $f^*=0.5$ on a logarithmic axis, for the run of Fig. 5 and 30 independent runs.

Trajectory of the Global Best

The left panel shows the coordinates of the global best particle: after a few iterations of large jumps, they settle at $x^*=1.5$ and $y^*=2.5$. The right panel plots the constraint value $x+y$. The global best starts infeasible ($x+y\approx 5.1$), becomes feasible after the first iteration and, after some wandering at $x+y\approx 3$, climbs to the limit $4$ from below, which is the signature of an active constraint: the optimum sits on the boundary.

0 20 40 60 80 100 0 1 2 3 4 5 Iteration t Coordinate value x (best) y (best) 0 20 40 60 80 100 3 4 5 Iteration t Constraint value x + y infeasible feasible
Fig. 7 – Global best, first 100 iterations. Dashed lines mark the exact solution.

How Much Do the Parameters Matter?

To see the influence of $w$, $c_1$, $c_2$ and $N$, the same problem was solved 30 times (seeds 0–29) for each of six settings, with 200 iterations. Since PSO does not reach the accuracy of DE here, we call a run successful when its error falls below $10^{-4}$. Fig. 8 shows the median error over the 30 runs; the table counts the successful runs and the number of iterations that they needed (median).

0 25 50 75 100 125 150 175 200 10−7 10−6 10−5 10−4 10−3 10−2 10−1 100 101 102 Iteration t Median error f̃ − f* (30 runs) w = 0.73, c₁ = c₂ = 1.50 (baseline) w = 0.90, c₁ = c₂ = 1.50 w = 0.40, c₁ = c₂ = 1.50 c₂ = 0, c₁ = 2.0 (no social term) c₁ = 0, c₂ = 2.0 (no memory term) N = 8 particles
Fig. 8 – Median error for six parameter settings (30 runs each).
SettingRuns with error < 10−4Median iterations neededMedian final error
w = 0.73, c1 = c2 = 1.50 (baseline)25 / 30942.5 × 10−5
w = 0.90, c1 = c2 = 1.500 / 30–1.2 × 10−3
w = 0.40, c1 = c2 = 1.5017 / 30376.2 × 10−5
c2 = 0, c1 = 2.0 (no social term)0 / 30–1.1 × 10−1
c1 = 0, c2 = 2.0 (no memory term)17 / 30776.0 × 10−5
N = 8 particles8 / 301183.0 × 10−4

The median number of iterations is taken over the successful runs only.

  • The baseline ($w=0.73$, $c_1=c_2=1.50$) is the most reliable setting and reaches the best median final error. It succeeded in 25 of 30 runs, needing a median of 94 iterations.
  • A large inertia ($w=0.9$) never succeeded: the particles keep too much momentum, overshoot the optimum again and again, and the swarm contracts too slowly to refine the solution within 200 iterations.
  • A small inertia ($w=0.4$) was the fastest (median 37 iterations) but failed in 13 of 30 runs: the swarm contracts quickly, and sometimes prematurely.
  • Without the social term ($c_2=0$) the particles do not exchange any information; they are 20 independent searchers pulled only towards their own best. This failed in every run (median final error $0.1$). The social term is what makes the swarm a swarm.
  • Without the memory term ($c_1=0$) all particles follow the global best only. This works surprisingly well on such a simple problem (17 of 30 runs), but with no diversity: every particle is drawn to the same point, which makes it a risky choice for harder problems.
  • A small swarm ($N=8$) succeeded in only 8 of 30 runs, because too few particles reduce diversity.
Caution. These numbers describe this particular two-variable problem and 30 runs per setting. They illustrate how the parameters act, not universal optimal values. In a quick additional test, linearly decreasing the inertia from 0.9 to 0.4, a popular recipe, gave a similar median error ($4\cdot10^{-5}$) to the constant constriction setting here. For a real problem, tune $N$, $w$, $c_1$ and $c_2$ on a few pilot runs and prefer settings that succeed in every run over settings that are merely fast.

Particle Swarm versus Differential Evolution

The two methods were run on the same problem, with the same swarm or population size (20), the same 200 iterations or generations and therefore the same 4020 evaluations, on the same 30 seeds. (The DE results come from the algorithm of the previous article, with $F=0.8$ and $CR=0.7$; the 30 runs reproduce the figures of that article: all runs reach $10^{-6}$, in a median of 94 generations.)

0 25 50 75 100 125 150 175 200 10−14 10−12 10−10 10−8 10−6 10−4 10−2 100 102 Iteration t (PSO) / generation g (DE) Median error f̃ − f* (30 runs) particle swarm (N = 20, w = 0.73, c = 1.50) differential evolution (NP = 20, F = 0.8, CR = 0.7) lines: median of 30 runs shading: 10th to 90th percentile
Fig. 9 – Particle swarm optimization against differential evolution. Median error of 30 runs of each method on the same problem with the same number of evaluations.
Iteration / generationPSO, median errorDE, median error
104.6 × 10−22.5 × 10−1
305.2 × 10−36.9 × 10−3
507.6 × 10−44.4 × 10−4
1006.5 × 10−53.6 × 10−7
2002.5 × 10−52.2 × 10−13

The two curves tell a clear story. PSO is faster in the beginning: after 10 iterations its median error is about five times smaller than that of DE, because the momentum and the pull towards the global best carry the whole swarm quickly into the right region. Around iteration 30 to 50 the two methods are about equal; the median iteration to reach an error of $10^{-2}$ is 26 for PSO and 28 for DE, and to reach $10^{-3}$ it is about 48 against 44. After that, however, DE takes over: its error falls geometrically, by a factor of ten every 15 to 18 generations, while the error of PSO flattens out at about $10^{-5}$. After 200 iterations, DE has an error of about $2\cdot10^{-13}$ (median; every run is below $2\cdot10^{-12}$), PSO of $2.5\cdot10^{-5}$ (median).

Why does the swarm slow down? A plausible explanation lies in how the two methods use their population. In DE a trial replaces its target only when it is better, and the steps are differences between population members, so the step size shrinks in proportion to the spread of the population while every member keeps its own position, preserving diversity. In PSO all particles are pulled towards the same best point $\mathbf{g}$: as they approach it, their velocities decay, the swarm collapses into a tiny cloud around $\mathbf{g}$, and it can improve only by random moves that must land in a very thin region: here the narrow wedge on the feasible side of the boundary, next to a penalty cliff. The basic algorithm has no guarantee of converging even to a local optimum, and this “stagnation” is a known weakness. Remedies exist (restarts, local topologies, a short local search at the end), but they add complexity.

The practical lesson is a nuanced one. PSO is an excellent tool when you need a good solution quickly or the last digits do not matter, and it is a convenient starting point for a final local polish. When high accuracy is required from a plain global search, differential evolution is the safer choice on this kind of problem. For a smooth, convex problem like this one, a gradient-based solver is, as in the previous article, far cheaper than either.

Result (seed 42, $N=20$, $w=0.7298$, $c_1=c_2=1.49618$, 200 iterations):
Best solution: $x = 1.496518$, $y = 2.503482$  –  objective $f = 0.50002435$
Constraint: $x + y = 4.000000 \le 4$ ✔  |  bounds $0\le x,y\le 10$ ✔
Analytic optimum: $(1.5,\,2.5)$, $f^*=0.5$  –  final error $2.4\cdot 10^{-5}$

Practical Guidance

  • Scale the variables. The velocities and the initial velocities scale with the box width of each variable, so wildly different ranges (for instance $[0,1]$ and $[0,10^6]$) distort the search. Rescale to comparable ranges.
  • Start from the constriction setting. $w=0.7298$ and $c_1=c_2=1.49618$ is a robust default; change it only for a reason.
  • Choose the budget in evaluations. The cost is $N\cdot T_{\max}$ evaluations; set $N$ from the dimension (20 to 50 is a common starting point) and $T_{\max}$ from the budget.
  • Run several seeds. PSO is stochastic. Agreement between independent runs is the best evidence that you found the global optimum.
  • Mind the boundaries and the speed. Decide explicitly what happens to particles that leave the box, and limit the velocities with $v_{\max}$ if the swarm behaves wildly.
  • Prefer a ring topology for hard problems. On multimodal landscapes, local neighbourhoods keep the swarm from collapsing onto the first good point it finds.
  • Polish at the end. A short run of a local, gradient-based optimizer started from the PSO solution turns a good answer into a precise one cheaply, which is exactly what this example needs.
  • Stop on convergence. Besides $T_{\max}$, monitor the swarm radius, the speed of the particles or the improvement of the global best value.

Summary of Key Formulas

StepFormulaDescription
Initialization$x_{i,j} = L_j + \text{rand}\cdot(U_j-L_j)$, $v_{i,j} = 0.2(\text{rand}-0.5)(U_j-L_j)$Uniform random positions, small random velocities
Velocity$\mathbf{v}_i = w\mathbf{v}_i + c_1\mathbf{r}_1\odot(\mathbf{p}_i-\mathbf{x}_i) + c_2\mathbf{r}_2\odot(\mathbf{g}-\mathbf{x}_i)$Inertia, memory and social term
Position$\mathbf{x}_i = \mathbf{x}_i + \mathbf{v}_i$Move, then clip to the bounds
Personal best$\mathbf{p}_i = \mathbf{x}_i$ if $f(\mathbf{x}_i) < f(\mathbf{p}_i)$Each particle remembers its best position
Global best$\mathbf{g} = \arg\min_i f(\mathbf{p}_i)$The swarm remembers its best position
Penalty$\tilde{f}=f+\rho\sum_k\max(0,g_k)$Exact if $\rho$ exceeds the Lagrange multiplier

References

  1. J. Kennedy and R. Eberhart, “Particle swarm optimization,” Proceedings of the IEEE International Conference on Neural Networks, 1995, 1942–1948.
  2. Y. Shi and R. Eberhart, “A modified particle swarm optimizer,” IEEE International Conference on Evolutionary Computation, 1998, 69–73.
  3. M. Clerc and J. Kennedy, “The particle swarm: explosion, stability, and convergence in a multidimensional complex space,” IEEE Transactions on Evolutionary Computation 6 (2002), 58–73.
  4. R. Poli, J. Kennedy and T. Blackwell, “Particle swarm optimization: an overview,” Swarm Intelligence 1 (2007), 33–57.
  5. K. Deb, “An efficient constraint handling method for genetic algorithms,” Computer Methods in Applied Mechanics and Engineering 186 (2000), 311–338.
  6. R. Storn and K. Price, “Differential Evolution – A Simple and Efficient Heuristic for Global Optimization over Continuous Spaces,” Journal of Global Optimization 11 (1997), 341–359 (for the comparison).
Share LinkedIn

Keep reading

Related articles

Searching...