[Python科学计算] 带约束的粒子群算法(PSO)手工实现

引言:

一个只熟悉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
  • 7
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值