实在是坚持不下去写CSDN 还是回家记录好啊哈哈 太温馨啦
坚持努力!不能摆烂三年!即使什么都研究不出来…哭了
群智能优化算法笔记Part1
教与学算法背景
教与学优化(Teaching-Learning Based Optimization,TLBO) 由印度学者Rao等2011年提出 原理说白了就是模仿学校找好老师教学生,学生请教好学生取长补短的过程,不断迭代优化,最终得到一个良好的结果。
教与学优化算法实现
import copy
import random
import numpy as np
import math
def initialization(pop, ub, lb, dim):
"""初始化函数"""
"""
pop 种群数量
dim 个体维度
ub 上边界
lb 下边界
X 输出的总群
"""
X = np.zeros([pop, dim])
for i in range(pop):
for j in range(dim):
X[i, j] = (ub[j] - lb[j]) * np.random.random() + lb[j]
return X
def BorderCheck(X, ub, lb, pop, dim):
"""边界检查函数"""
for i in range(pop):
for j in range(dim):
if X[i, j] > ub[j]:
X[i, j] = ub[j]
if X[i, j] < lb[j]:
X[i, j] = lb[j]
return X
def CaculateFitness(X, fun):
"""计算种群的所有个体的适应度值"""
pop = X.shape[0]
fitness = np.zeros([pop, 1])
for i in range(pop):
fitness[i] = fun(X[i, :])
return fitness
def SortFitness(Fit):
"""对适应度进行排序"""
fitness = np.sort(Fit, axis=0) # 按列排序
index = np.argsort(Fit, axis=0) # 索引
return fitness, index
def SortPosition(X, index):
"""根据适应度值的大小对个体位置进行排序"""
Xnew = np.zeros(X.shape)
for i in range(X.shape[0]):
Xnew[i, :] = X[index[i], :]
return Xnew
def TLBO(pop,dim,lb,ub,maxIter,fun):
"""教与学"""
X=initialization(pop,ub,lb,dim)
fitness=CaculateFitness(X,fun)
GbestScore=np.min(fitness)
indexBest=np.argmin(fitness)
GbestPosition=np.zeros([1,dim])
GbestPosition[0,:]=copy.copy(X[indexBest,:])
Curve=np.zeros([maxIter,1])
for t in range(maxIter):
print('第'+str(t),'次迭代')
for i in range(pop):
#教阶段
Xmean=np.mean(X)
indexBest=np.argmin(fitness)
Xteacher=copy.copy(X[indexBest,:])
beta=random.randint(0,1)
Xnew=X[i,:]+np.random.random(dim)*(Xteacher-beta*Xmean)
#边界检查
for j in range(dim):
if Xnew[j]>ub[j]:
Xnew[j]=ub[j]
if Xnew[j]<lb[j]:
Xnew[j]=lb[j]
#计算适应度值
fitnessNew=fun(Xnew)
#位置更新
if fitnessNew<fitness[i]:
X[i,:]=copy.copy(Xnew)
fitness[i]=copy.copy(fitnessNew)
#学阶段
p=random.randint(0,dim-1)
while i==p:
p=random.randint(0,dim-1)
#学阶段位置更新
if fitness[i]<fitness[p]:
Xnew=X[i,:]+np.random.random(dim)*(X[i,:]-X[p,:])
else:
Xnew = X[i, :] - np.random.random(dim) * (X[i, :] - X[p, :])
#边界检查
for j in range(dim):
if Xnew[j]>ub[j]:
Xnew[j]=ub[j]
if Xnew[j]<lb[j]:
Xnew[j]=lb[j]
#若位置更优 更新先前解
fitnessNew=fun(Xnew)
if fitnessNew<fitness[i]:
X[i,:]=copy.copy(Xnew)
fitness[i]=fitnessNew
fitness=CaculateFitness(X,fun)
indexBest=np.argmin(fitness)
if fitness[indexBest]<=GbestScore:
GbestScore=copy.copy(fitness[indexBest])
GbestPosition[0,:]=copy.copy(X[indexBest,:])
Curve[t]=GbestScore
return GbestScore,GbestPosition,Curve
解决寻找最小值问题
#适应度函数二元方程 dim也要2维
def fun(X):
O=X[0]**2+X[1]**2
return O
适应度值收敛结果