PSO in Machine Learning: Tune Your Model Without Guesswork

PSO in machine learning

PSO in machine learning solves a problem almost every student hits in a final year ML project: the model works, but the accuracy is stuck, and you do not know which hyperparameters to change. Trying values by hand takes days, and grid search can run for hours on a college laptop.

Particle Swarm Optimization (PSO) searches for good settings for you, and it usually needs far fewer trials. This guide shows real ML projects you can apply it to, explains PSO in plain words, and gives you tested Python code to tune your own model.

Reference ML Projects to Apply PSO On

Open one of these projects first. Each one trains a model whose hyperparameters you can tune with PSO, so you will see a before-and-after result in your own project.

For more options, see our list of machine learning projects with source code.

ItemDetails
TopicPSO in Machine Learning
Full FormParticle Swarm Optimization
Introduced ByKennedy and Eberhart, 1995
Used ForHyperparameter tuning, feature selection, neural network weights
LanguagePython
LibrariesNumPy, Scikit-learn, PySwarms (optional)
DifficultyIntermediate
Best ForBCA, MCA, B.Tech ML and AI projects
Year2026
DeveloperUpdategadh

What Is PSO in Machine Learning?

PSO in machine learning is an optimization method that finds good values for a model’s settings by moving a group of candidate solutions, called particles, through the search space. Each particle remembers its own best result, and the whole group shares the best result found so far. Over a few rounds, the particles gather around the settings that give the highest score.

The idea comes from how a flock of birds finds food: each bird follows its own experience and the bird that is closest to the food.

The Problem PSO Solves for Students

  • Guessing hyperparameters: values like the number of trees or tree depth are picked randomly and never improved.
  • Slow grid search: checking every combination grows very fast. Three settings with 10 values each already means 1,000 training runs.
  • No clear story for the viva: “I changed numbers until it worked” is a weak answer. “I used PSO to search the settings” is a strong one.

How PSO Works, Step by Step

How PSO in machine learning tunes a model: start swarm, score, move particles, best model
How PSO tunes a machine learning model
  1. Start the swarm: place particles at random points, where each point is one set of hyperparameters.
  2. Score each particle: train the model with those settings and measure accuracy with cross-validation.
  3. Remember the best: each particle keeps its personal best (pbest), and the swarm keeps the global best (gbest).
  4. Update velocity: each particle moves using three pulls: its current direction, its own best and the swarm’s best.
  5. Move and repeat: particles move to new points, get scored again, and the loop repeats for a fixed number of rounds.
  6. Use the winner: the global best settings are your tuned model.

The velocity update is: v = w*v + c1*r1*(pbest - x) + c2*r2*(gbest - x). Here w is inertia, c1 and c2 control how strongly a particle follows its own best and the swarm’s best, and r1, r2 are random numbers between 0 and 1. Common starting values are w = 0.7 and c1 = c2 = 1.5.

MethodHow It SearchesSpeedBest When
Grid searchTries every combination in a fixed gridSlow for many settingsVery few settings with few values
Random searchTries random combinationsFast, but does not learnQuick first check
PSOParticles learn from each other and move toward better scoresFewer trials for a good resultSeveral settings, limited time
PSO in machine learning compared with grid search and random search
Grid search vs random search vs PSO

Scikit-learn explains grid and random search in its hyperparameter tuning guide, which is useful to read before you compare them with PSO.

Python Code: Tune a Random Forest with PSO

This code tunes two settings of a Random Forest, the number of trees and the maximum depth, using the breast cancer dataset that comes with scikit-learn. We tested it: it runs in about a minute on a normal laptop.

import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score

X, y = load_breast_cancer(return_X_y=True)

def score(p):
    n_est, depth = int(p[0]), int(p[1])
    model = RandomForestClassifier(n_estimators=n_est, max_depth=depth, random_state=42)
    return cross_val_score(model, X, y, cv=3).mean()

low, high = np.array([10, 2]), np.array([200, 20])
n, iters, w, c1, c2 = 10, 15, 0.7, 1.5, 1.5
rng = np.random.default_rng(42)

pos = rng.uniform(low, high, (n, 2))
vel = np.zeros((n, 2))
pbest = pos.copy()
pbest_score = np.array([score(p) for p in pos])
gbest = pbest[pbest_score.argmax()].copy()

for _ in range(iters):
    r1, r2 = rng.random((n, 2)), rng.random((n, 2))
    vel = w * vel + c1 * r1 * (pbest - pos) + c2 * r2 * (gbest - pos)
    pos = np.clip(pos + vel, low, high)
    for i, p in enumerate(pos):
        s = score(p)
        if s > pbest_score[i]:
            pbest[i], pbest_score[i] = p.copy(), s
    gbest = pbest[pbest_score.argmax()].copy()

print("Best n_estimators, max_depth:", gbest.astype(int))
print("Best accuracy:", round(pbest_score.max(), 4))

In our run, the default Random Forest scored 95.78% accuracy, and the PSO-tuned model scored 96.31% using only 59 trees instead of 100. On this clean dataset the gain is small, which is normal. The bigger the gap between your current settings and good ones, the more PSO helps. To use it in your own project, replace the dataset and the two settings in score().

If you prefer a ready library, PySwarms gives you PSO in a few lines, but writing it yourself, as above, is easier to explain in a viva.

Where Else PSO Is Used in Machine Learning

  • Feature selection: each particle picks a subset of features, and the score rewards high accuracy with fewer features. Read our guide on feature selection techniques to compare it with other methods.
  • Neural network training: PSO can search weights or learning rates, as an alternative to the optimization algorithms for neural networks like Adam.
  • Clustering: PSO can find good cluster centres instead of random starting points.

Common Mistakes When Using PSO

  1. No bounds: without np.clip, particles fly to impossible values like negative tree counts.
  2. Scoring on training data: always use cross-validation, or PSO will pick settings that overfit.
  3. Too many particles: 10 to 30 particles and 15 to 50 rounds are enough for a student project.
  4. No baseline: always report the accuracy before and after PSO, or the examiner cannot see the benefit.

Viva Questions on PSO in Machine Learning

What is the full form of PSO?

PSO stands for Particle Swarm Optimization. It was introduced by James Kennedy and Russell Eberhart in 1995.

What are pbest and gbest?

pbest is the best position one particle has found so far. gbest is the best position found by the whole swarm.

PSO reaches good settings with fewer training runs because particles learn from each other, while grid search checks every combination.

What does the inertia weight do?

It controls how much a particle keeps moving in its current direction. A higher value explores more, and a lower value settles faster.

Final Thoughts

PSO in machine learning turns “I guessed the settings” into a clear, repeatable method. Pick one of the reference projects above, record its accuracy, run the PSO code on its model, and show the before-and-after result. That simple comparison makes your ML project stronger and gives you a confident answer in the viva.

Get a Ready ML Project

Want a complete machine learning project with source code, report and PPT? Explore our ready projects and spend your time understanding and presenting it.

Get This Project Now

Watch project demos and setup guides on our YouTube channel.

Subscribe to DecodeIT2 on YouTube

Frequently Asked Questions

For several hyperparameters, PSO usually finds good settings with fewer training runs. For one or two settings with few values, grid search is simple and good enough.

Can I use PSO for feature selection?

Yes. Each particle represents a set of selected features, and the score rewards high accuracy with fewer features.

Is PSO a machine learning algorithm?

No. PSO is an optimization algorithm. In machine learning it is used to improve a model, for example by tuning its hyperparameters or selecting features.

Which Python library is used for PSO?

PySwarms is the most common library. You can also write PSO with NumPy in about 30 lines, as shown in this post.

Written by Rishabh Saini Founder, UpdateGadh

Rishabh Saini is the founder of UpdateGadh. He has 5 years of experience building PHP, Python, Java, AI and ML projects, and works on projects with the latest and trending technologies. He has helped 2,000+ BCA, MCA and B.Tech students with final year projects. Every project on UpdateGadh is built and tested by him before it is published.

Leave a Reply

Your email address will not be published. Required fields are marked *