Particle Swarm Optimization in Python

Hello everyone and welcome !

In this post, I’m going to show you a basic concept and Python code of Particle Swarm Optimization algorithm (PSO algorithm) for solving optimization problems.

I’m going to test the performance of this Particle Swarm Optimization in solving a famous benchmark problem.

It is possible to customize this Python code to solve various optimization problems in your fields.

Did you know that Particle Swarm Optimization (PSO) is one of the most popular stochastic optimization algorithms in our research community? Let’s have a look at this data from Scopus.

Here are the details of the benchmark problem to test the performance of the Particle Swarm Optimization.

Let’s see how this Particle Swarm Optimization algorithm works:

For more videos like this, check my YouTube channel here.

import random
import math
import matplotlib.pyplot as plt
import numpy as np
# ------------------------------------------------------------------------------
# TO CUSTOMIZE THIS PSO CODE TO SOLVE UNCONSTRAINED OPTIMIZATION PROBLEMS, CHANGE THE PARAMETERS IN THIS SECTION ONLY:
# THE FOLLOWING PARAMETERS MUST BE CHANGED.
def objective_function(X):
    A = 10
    y = A*2 + sum([(x**2 - A * np.cos(2 * math.pi * x)) for x in X])
    return y
 
bounds = [(-5.12, 5.12), (-5.12, 5.12)]  # upper and lower bounds of variables
nv = 2  # number of variables
mm = -1  # if minimization problem, mm = -1; if maximization problem, mm = 1
 
# THE FOLLOWING PARAMETERS ARE OPTIONAL
particle_size = 50  # number of particles
iterations = 100  # max number of iterations
w = 0.75  # inertia constant
c1 = 1  # cognative constant
c2 = 2  # social constant
# END OF THE CUSTOMIZATION SECTION
# ------------------------------------------------------------------------------
# Visualization
fig = plt.figure()
ax = fig.add_subplot()
fig.show()
# ------------------------------------------------------------------------------
class Particle:
    def __init__(self, bounds):
        self.particle_position = []  # particle position
        self.particle_velocity = []  # particle velocity
        self.local_best_particle_position = []  # best position of the particle
        self.fitness_local_best_particle_position = initial_fitness  # initial objective function value of the best particle position
        self.fitness_particle_position = initial_fitness  # objective function value of the particle position
 
        for i in range(nv):
            self.particle_position.append(
                random.uniform(bounds[i][0], bounds[i][1]))  # generate random initial position
            self.particle_velocity.append(random.uniform(-1, 1))  # generate random initial velocity
 
    def evaluate(self, objective_function):
.
.
.
Sorry! This is only a half of the code.

Notice: It would take you from 1 to 3 hours to re-type the Python code yourself; or with just €1.99 (the cost of a cup of coffee), you can download/copy the whole Python code within 2 minutes. It’s your choice to make.

Original price is €4.99 but today it’s only €1.99 (save €3 today – available for a limited time only)

Download the whole Python code here (Membership Code ID: 019)

No need to build the Python code from scratch because it’s very time-consuming. My idol, Jim Rohn, once said: “Time is more value than money. You can get more money, but you cannot get more time”. If you think this code can be used in your research/teaching work, you should download it and then customize/modify/apply it to your work, without any obligation of citing the original source if you don’t want. However, redistribution (i.e., downloading the code/script here and then making it available on another site on the Internet) is strictly prohibited.

If you have any question or problem, please contact Dr. Panda by email: learnwithpanda2018@gmail.com

Thank you very much and good luck with your research!

41 Replies to “Particle Swarm Optimization in Python”

  1. please , i want to talk to you regarding my assignment on PSO . I am ready to pay , as well. i have dropped my email-address

  2. Hi Sir how can use the PSO for multi objective optimization. Also let me know how to modify the code for multi objective problems.

    1. Hello, I don’t have PSO code for specific problems. You may need to customize this code to solve the problems in your fields.

      1. Hello sir. Do you have code in phyton for hybrid power plant optimization, especially GA? If you have or maybe can make it I’m ready to pay, I need help from you.

    1. Hello, a simple method is to convert the max to min problem. For example, max y = f(x), convert: min z = 1/f(x), if f(x) > 0

  3. Do you have the source code of Social Spider Algorithm? I need it soon…any language with Optimization Functions implemented

  4. Could you please tell me how this PsO helps to identify the segments that going to be actif in a path in transportation problem?

      1. Hloo sir….I want to use PSO algorithm using python in vehicle routing problem….can you please help me…it’s my mini project work for mtech…I am trying this for past 3 months but I didn’t get any output…can you please help me to finish my project…it’s a request sir

  5. Hello can you please suggest me some links to codes where i will get idea of implementing PSO in my image classification

  6. Good evening, Doctor. I am a graduate student. Can I use Particle Swarm Optimization to select features from the database ?

Leave a Reply

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