import numpy as np
from matplotlib import pyplot as plt
import random # 初始化种群
def init(n_pop, lb, ub, nd):
"""
:param n_pop: 种群
:param lb: 下界
:param ub: 上界
:param nd: 维数
"""
p = lb + (ub - lb) * np.random.rand(n_pop, nd)
return p # 适应度函数
def sphere(x):
y = np.sum(x ** 2, 1)
return y def Ackley_1(x):
n, d = x.shape
y = -20 * np.exp(-0.02 * np.sqrt(1 / d * np.sum(x ** 2, 1))) - np.exp(
1 / d * np.sum(np.cos(2 * np.pi * x), 1)) + 20 + np.e
return y def Ackley_2(x):
y = -200 * np.exp(-0.02 * np.sqrt(x[:, 0] ** 2 + x[:, 1] ** 2))
return y def Ackley_3(x):
y = -200 * np.exp(-0.02 * np.sqrt(x[:, 0] ** 2 + x[:, 1] ** 2)) + 5 * np.exp(
np.cos(3 * x[:, 0]) + np.sin(3 * x[:, 1]))
return y def Ackley_4(x, y=0):
_, d = x.shape
for i in range(1, d):
y += np.exp(-0.2 * np.sqrt(x[:, i - 1] ** 2 + x[:, i] ** 2)) + 3 * (
np.cos(2 * x[:, i - 1]) + np.sin(2 * x[:, i]))
return y def Adjiman(x):
y = np.cos(x[:, 0]) * np.sin(x[:, 1]) - x[:, 0] / (x[:, 1] ** 2 + 1)
return y def Alpine(x):
y = np.sum(np.abs(x * np.sin(x) + 0.1 * x), 1)
return y def Alpine2(x):
y = np.prod(np.sqrt(x) * np.sin(x), axis=1)
return y def Bartels(x):
y = np.abs(x[:, 0] ** 2 + x[:, 1] ** 2 + x[:, 0] * x[:, 1]) + np.abs(np.sin(x[:, 0])) + np.abs(np.c
return y def Beale(x):
y = (1.5 - x[:, 0] + x[:, 0] * x[:, 1]) ** 2 + (2.25 - x[:, 0] + x[:, 0] * x[:, 1] ** 2) ** 2 + (
2.625 - x[:, 0] + x[:, 0] * x[:, 1] ** 3) ** 2
return y f_score = sphere # 函数句柄 # Levy飞行Beale
def Levy(nd, beta=1.5):
num = np.random.gamma(1 + beta) * np.sin(np.pi * beta / 2)
den = np.random.gamma((1 + beta) / 2) * beta * 2 ** ((beta - 1) / 2)
sigma_u = (num / den) ** (1 / beta) u = np.random.normal(0, sigma_u ** 2, (1, nd))
v = np.random.normal(0, 1, (1, nd)) z = u / (np.abs(v) ** (1 / beta))
return z def FPA(Max_g, n_pop, Pop, nd, lb, ub, detail): # FPA算法
"""
:param Max_g: 迭代次数
:param n_pop: 种群数目
:param Pop: 花粉配子
:param nd: 维数
:param lb: 下界
:param ub: 上界
:param detail: 显示详细信息
"""
# 计算初始种群中最好个体适应度值
pop_score = f_score(Pop)
g_best = np.min(pop_score)
g_best_loc = np.argmin(pop_score)
g_best_p = Pop[g_best_loc, :].copy() # 问题设置
p = 0.8
best_fit = np.empty((Max_g,))
# 迭代
for it in range(1, Max_g + 1):
for i in range(n_pop):
if np.random.rand() < p:
new_pop = Pop[i, :] + Levy(nd) * (g_best_p - Pop[i, :])
new_pop = np.clip(new_pop, lb, ub) # 越界处理
else:
idx = random.sample(list(range(n_pop)), 2)
new_pop = Pop[i, :] + np.random.rand() * (Pop[idx[1], :] - Pop[idx[0], :])
new_pop = np.clip(new_pop, lb, ub) # 越界处理
if f_score(new_pop.reshape((1, -1))) < f_score(Pop[i, :].reshape((1, -1))):
Pop[i, :] = new_pop
# 计算更新后种群中最好个体适应度值
pop_score = f_score(Pop)
new_g_best = np.min(pop_score)
new_g_best_loc = np.argmin(pop_score) if new_g_best < g_best:
g_best = new_g_best
g_best_p = Pop[new_g_best_loc, :].copy()
best_fit[it - 1] = g_best if detail:
print("----------------{}/{}--------------".format(it, Max_g))
print(g_best)
print(g_best_p) return best_fit, g_best if __name__ == "__main__":
pop = init(30, -100, 100, 2)
fitness, g_best = FPA(1000, 30, pop, 2, -100, 100, True) # 可视化
plt.figure()
# plt.plot(fitness)
plt.semilogy(fitness)
# 可视化
# fig = plt.figure()
# plt.plot(p1, fit)
plt.show()
花授粉算法Matlab代码
% 清屏和工作空间变量
clc
clear
Step 1: 问题定义
npop = 30; % 种群数目
dpop = 2; % 种群维数
ub = 100; % 种群的上界
lb = -100; % 种群的下界
Step 2: 初始化种群
pop = lb + rand(npop, dpop).*(ub - lb); % pop是初始种群
Step 3:适应度函数
fScore = @ sphere
Step 4:Levy飞行
levy = @ Levy
Step 5:计算初始种群最好的适应度值
popScore = fScore(pop);
[bestscore, loc] = min(popScore);
bestpop = pop(loc, :);
Step 6:参数设置
iterMax = 1000; % 最大迭代次数
p = 0.8; % 转换概率
BestScore = ones(iterMax, 1);
Step 7:越界处理
Clip = @ clip; % 越界处理函数
Step 8:迭代
for it=1:iterMax
for i = 1:npop
if rand < p
newpop = pop(i, :) + levy(1, dpop).*(bestpop - pop(i, :)); % 异花授粉
else
idx = randsample(30, 2);
newpop = pop(i, :) + rand*(pop(idx(1), :) - pop(idx(2), :)); % 自花授粉
end
newpop = Clip(newpop, ub, lb); % 越界处理
if fScore(newpop) < fScore(pop(i, :))
pop(i, :) = newpop; % 更新种群
end
end
popScore = fScore(pop);
[newBestScore, Loc] = min(popScore);
if newBestScore < bestscore
bestscore = newBestScore;
bestpop = pop(loc, :);
end
BestScore(it) = bestscore;
disp(['Iteration ' num2str(it) ': Best Cost = ' num2str(bestscore)]);
disp(['Bestpop ' num2str(bestpop)])
end
Step 9:可视化
figure
semilogy(BestScore)
% plot(BestScore)
xlim([0 1000])
xlabel('迭代次数')
ylabel('适应度')
title('FPA')

function L=Levy(d)
%% Levy飞行
beta=3/2;
sigma=(gamma(1+beta)*sin(pi*beta/2)/(gamma((1+beta)/2)*beta*2^((beta-1)/2)))^(1/beta);
u=random('normal', 0, sigma, 1, d);
v=random('normal', 0, 1, 1, d);
L=0.01*u./abs(v).^(1/beta);
end
function s=simplebounds(s,Lb,Ub)
%% 越界处理函数
ns_tmp=s;
I=ns_tmp<Lb;
ns_tmp(I)=Lb(I);
J=ns_tmp>Ub;
ns_tmp(J)=Ub(J);
s=ns_tmp;
end
function [y] = Sphere(xx)
%% 目标函数
d = length(xx);
sum = 0;
for ii = 1:d
xi = xx(ii);
sum = sum + xi^2;
end y = sum;
end

  

花授粉优化算法-python/matlab的更多相关文章

  1. 群智能优化算法-测试函数matlab源码

    群智能优化算法测试函数matlab源代码 global M; creatematrix(2); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %画ackley图. %%%% ...

  2. 粒子群优化算法-python实现

    PSOIndividual.py import numpy as np import ObjFunction import copy class PSOIndividual: ''' individu ...

  3. 计算智能(CI)之粒子群优化算法(PSO)(一)

    欢迎大家关注我们的网站和系列教程:http://www.tensorflownews.com/,学习更多的机器学习.深度学习的知识! 计算智能(Computational Intelligence , ...

  4. [matlab] 6.粒子群优化算法

    粒子群优化(PSO, particle swarm optimization)算法是计算智能领域,除了蚁群算法,鱼群算法之外的一种群体智能的优化算法,该算法最早由Kennedy和Eberhart在19 ...

  5. 粒子群优化算法PSO及matlab实现

    算法学习自:MATLAB与机器学习教学视频 1.粒子群优化算法概述 粒子群优化(PSO, particle swarm optimization)算法是计算智能领域,除了蚁群算法,鱼群算法之外的一种群 ...

  6. MATLAB粒子群优化算法(PSO)

    MATLAB粒子群优化算法(PSO) 作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/ 一.介绍 粒子群优化算法(Particle Swarm Optim ...

  7. 模拟退火算法SA原理及python、java、php、c++语言代码实现TSP旅行商问题,智能优化算法,随机寻优算法,全局最短路径

    模拟退火算法SA原理及python.java.php.c++语言代码实现TSP旅行商问题,智能优化算法,随机寻优算法,全局最短路径 模拟退火算法(Simulated Annealing,SA)最早的思 ...

  8. 粒子群优化算法对BP神经网络优化 Matlab实现

    1.粒子群优化算法 粒子群算法(particle swarm optimization,PSO)由Kennedy和Eberhart在1995年提出,该算法模拟鸟集群飞行觅食的行为,鸟之间通过集体的协作 ...

  9. 分别使用 Python 和 Math.Net 调用优化算法

    1. Rosenbrock 函数 在数学最优化中,Rosenbrock 函数是一个用来测试最优化算法性能的非凸函数,由Howard Harry Rosenbrock 在 1960 年提出 .也称为 R ...

随机推荐

  1. [luogu7078]贪吃蛇

    结论:若$a_{n}-a_{1}\ge a_{2}$,那么一定会吃掉 证明:分类讨论,若$a_{n-1}$也吃掉了$a_{2}$,就说明$a_{n-1}$之后不会被吃掉,而$a_{n-1}-a_{2} ...

  2. SSM(Spring-MyBatis-SpringMVC)框架整合【完整版】

    整合SSM 01 基本配置文件的关系 web.xml配置DispatcherServlet 02 需要的maven依赖 <!--依赖 1.junit 2.数据库连接池 3.servlet 4.j ...

  3. CF1264D1 Beautiful Bracket Sequence (easy version)

    考虑在一个确定的括号序列中,我们可以枚举中间位置,按左右最长延伸出去的答案计算. 我们很自然的思考,我们直接维护左右两边,在删除一些字符后能够延伸的最长长度. 我们设\(f_{i,j}\)为\(i\) ...

  4. 2021.9.30 Codeforces 中档题四道

    Codeforces 1528D It's a bird! No, it's a plane! No, it's AaParsa!(*2500) 考虑以每个点为源点跑一遍最短路,每次取出当前距离最小的 ...

  5. 洛谷 P3647 [APIO2014]连珠线(换根 dp)

    题面传送门 题意: 桌子上有 \(1\) 个珠子,你要进行 \(n-1\) 次操作,每次操作有以下两种类型: 拿出一个新珠子,并选择一个桌子上的珠子,在它们之间连一条红线 选择两个由红线相连的珠子 \ ...

  6. DirectX12 3D 游戏开发与实战第七章内容(上)

    利用Direct3D绘制几何体(续) 学习目标 学会一种无须每帧都要刷新命令队列的渲染流程,以此来优化性能 了解另外两种根签名参数类型:根常量和根描述符 探索如何在程序中生成和绘制常见的几何体:如栅格 ...

  7. R 语言实战-Part 4 笔记

    R 语言实战(第二版) part 4 高级方法 -------------第13章 广义线性模型------------------ #前面分析了线性模型中的回归和方差分析,前提都是假设因变量服从正态 ...

  8. 【GS文献】植物育种中基因组选择的方法、模型及展望

    目录 1. GS/GP在植物育种中的角色 2. GP模型应用 3. GP模型的准确性 4. 植物育种的GS展望 5. 小结 Genomic SelectioninPlant Breeding: Met ...

  9. Redis集合解决大数据筛选

    Redis集合:集合是什么,就是一堆确定的数据放在一起,数学上集合有交集.并集的概念,这个就可以用来做大数据的筛选功能. 以商品为例,假如商品有颜色和分类.价格区间等属性. 给所有统一颜色的商品放一个 ...

  10. Kubernetes-存储(一)

    前言 本篇是Kubernetes第十二篇,大家一定要把环境搭建起来,看是解决不了问题的,必须实战. Kubernetes系列文章: Kubernetes介绍 Kubernetes环境搭建 Kubern ...