引言:
一个只熟悉MATLAB安装与卸载的Py选手遇到Suganthan Assignment 1
PSO算法原理及其变种版本在我之前的博客中有写过,本文不赘。
传送门:https://blog.csdn.net/hush19/article/details/113649013?spm=1001.2014.3001.5502
代码拆解:
Part 1:遇事不决先引包
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@FileName: PSO.py
@Abstract: PSO of K(w*v+c1*rand1*(pbest-x)+c2*rand2*(gbest-x)) with constraints
@Time: 2021/02/21 21:34:37
@Requirements: numpy, matplotlib
@Author: WangZy ntu.wangzy@gmail.com
@Version: -
'''
import numpy as np
from numpy import e, cos, sin, log, sqrt
import random
import matplotlib.pyplot as plt
注意:用矩阵实现速度远快于其它方法。
Part 2:类的初始化定义
class PSOKW:
def __init__(self,
population_size=50,
max_iter=1000,
dim=None,
fitness=None,
constraints=None):
'''
Particle Swarm Optimization Constraint Optimization
Args:
population_size (int): The number of particles 种群数量
max_iter (int): Max iteration 最大迭代次数
dim (int): Dimension of solution 决策变量维度
fitness (callable function): Fitness function 适应度函数
constraints (list): Standard Constraints 标准约束集
'''
self.c1 = 1.5 #cognition component 认知系数
self.c2 = 2.5 #social component 社会系数
self.w = 1 # Gradually reduce to 0.1 逐渐降低到0.1
self.kai = 0.453 #Capital K 大K
self.vmax = 4 # max velocity
self.population_size = population_size
self.max_iter = max_iter
self.dim = dim
self.x_recorder = []
self.fit_recorder = []
# Initialize as zero matrix
self.X = np.zeros((self.population_size, self.dim)) #Size: N*D
self.V = np.zeros((self.population_size, self.dim))
self.pbest = np.zeros((self.populatio