Python particle swarm algorithm

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Import PySwarms
import pyswarms as ps
from pyswarms.utils.functions import single_obj as fx
from pyswarms.single.global_best import GlobalBestPSO

1. Pyswarms implements particle swarm algorithm

1.1. Custom functions

Create a custom function, the independent variable x is a two-dimensional matrix, the dimension is shape(n_particles,n_dimension), each row is a particle, each column is a dimension, and the return value of the custom function is a one-dimensional matrix. Each element in the matrix is ​​the value returned by each particle input to the objective function. In addition, the custom function can also have some coefficients. In the example I give below, a coefficient a is given. The custom function I gave is: f (x) = a ∗ (x 1 2 + x 2 2) f(x) = a*(x_1^2 + x_2^2)f(x)=a(x12+x22)

def SelfDefinedFunc(x , a):
    j = a * ((x ** 2.0).sum(axis=1))
    return j
# 输入一个二维矩阵,观察函数的输出值,进一步了解下自定义的函数。
x=np.array([[1,1],[2,2]])
SelfDefinedFunc(x,2)
array([ 4., 16.])

1.2. Defining constraints

The ranges of the independent variables that define the two dimensions are (1,9) and (3,10) respectively.

x_max = (9,10)
x_min = (1,3)
bounds = (x_min, x_max)

1.3. Use particle swarm algorithm for optimization solution

# instatiate the optimizer

options = {
    
    'c1': 0.5, 'c2': 0.3, 'w': 0.9} # 粒子群算法的参数
optimizer = GlobalBestPSO(n_particles=20, dimensions=2, options=options, bounds=bounds)

# now run the optimization, pass a=1 and b=100 as a tuple assigned to args

cost, pos = optimizer.optimize(SelfDefinedFunc, iters=1000,a = 2)  # a就是自定义函数的参数
print(cost , pos)
2020-07-21 11:51:58,850 - pyswarms.single.global_best - INFO - Optimize for 1000 iters with {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
pyswarms.single.global_best: 100%|███████████████████████████████████████████████████████████|1000/1000, best_cost=20.4
2020-07-21 11:52:00,856 - pyswarms.single.global_best - INFO - Optimization finished | best cost: 20.411660581634884, best pos: [1.03786661 3.02136777]


20.411660581634884 [1.03786661 3.02136777]

1.4. Conclusion

pyswarms is very simple to implement particle swarm optimization, but the problem is that this package cannot add constraint equations, so it is basically not good to solve optimization problems.

2. Pyswarm implements particle swarm algorithm

2.1. Custom function

Particle swarm algorithm will minimize the objective function

from pyswarm import pso

def banana(x):
    x1 = x[0]
    x2 = x[1]
    return x1**2 + x2**2
banana([1,2])
5

2.2. Define constraints

def con1(x):
    x1 = x[0]
    x2 = x[1]
    return x1-x2
def con2(x):
    x1 = x[0]
    x2 = x[1]
    return x1-x2-0.5

lb = [-3, 1]
ub = [2, 6]

2.3. Use particle swarm algorithm for optimization solution

I only impose some explanations on the constraints, and the others are very simple. You can see it at a glance, so I won't elaborate on it. Adding constraints mainly depends on the following two parameters.

ieqcons : list

A list of functions of length n such that ieqcons[j](x,*args) >= 0.0 in a successfully optimized problem (Default: empty list, [])

f_ieqcons : function

Returns a 1-D array in which each element must be greater or equal to 0.0 in a successfully optimized problem. If f_ieqcons is specified, ieqcons is ignored (Default: None)

xopt, fopt = pso(banana, lb, ub, f_ieqcons=None,ieqcons=[con1 , con2], args=(), kwargs={
    
    },
    swarmsize=100, omega=0.5, phip=0.5, phig=0.5, maxiter=100, minstep=1e-8,
    minfunc=1e-8, debug=False)
print(xopt , fopt)
Stopping search: Swarm best position change less than 1e-08
[1.50000002 1.        ] 3.250000048714665

2.4. Conclusion

Using pyswarm, it can be achieved perfectly, and the objective function with constraints is solved.

Reference link

https://pythonhosted.org/pyswarm/

Code acquisition

The code is in github

Guess you like

Origin blog.csdn.net/qq_39805362/article/details/107486044