简易粒子群算法求解目标函数最小值附python代码

我是小白

 

本程序结束条件设定为迭代次数

vscode代码如下:小白写的比较繁琐QAQ

#粒子群算法
import random
#粒子群
N=3#种群数量
step=5#迭代次数

#step1 初始化
fout=[]#目标函数输出值
xout=[]#储存坐标值
pbest=[]
v=[]
gbest=[]


for i in range(N):
    v1=random.randint(-10,10)
    v2=random.randint(-10,10)
    x1=random.randint(-10,10)
    x2=random.randint(-10,10)
    f=x1**2+x2**2
    fout.append(f)
    pbest.append([x1,x2])
    xout.append([x1,x2])
    v.append([v1,v2])
index=(fout.index(min(fout)))
gbest.append(pbest[index])
print(f'初始化后的gbest为{gbest}')

#根据自身的历史最优位置和全局的最优位置,更新每个粒子的速度和位置
w=0.5#权重
c=2#学习系数
r=random.randint(0,1)
count=0#迭代计数
while count < step:
    count=count+1

    #更新所有变量
    for i in range(N):
        v[i][0]=w*v[i][0]+c*r*(pbest[i][0]-xout[i][0])+c*r*(gbest[0][0]-xout[i][0])
        v[i][1]=w*v[i][1]+c*r*(pbest[i][1]-xout[i][1])+c*r*(gbest[0][1]-xout[i][1])
        xout[i][0]=xout[i][0]+v[i][0]
        xout[i][1]=xout[i][1]+v[i][1]
    print(f'第{count}次迭代时候的v为{v},xout为{xout}')
    #评估粒子的适应度函数值
    for i in range(N):
        if xout[i][0]**2+xout[i][1]**2<fout[i]:
            fout[i]=xout[i][0]**2+xout[i][1]**2
            pbest[i][0]=xout[i][0]
            pbest[i][1]=xout[i][1]
        else:
            fout[i]=fout[i]
            pbest[i][0]=pbest[i][0]
            pbest[i][1]=pbest[i][1]
    index=(fout.index(min(fout)))
    gbest.clear()
    gbest.append(pbest[index])
    print(f'第{count}次的迭代的gbest值为{gbest},此时最优值为{min(fout)}')








    
    

运行结果:

 

  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用遗传算法求解香蕉函数最小值Python 代码示例: ```python import random # 定义香蕉函数 def banana_function(x, y): return (1 - x)**2 + 100 * (y - x**2)**2 # 定义个体类 class Individual: def __init__(self, x, y): self.x = x self.y = y self.fitness = banana_function(x, y) # 定义遗传算法类 class GeneticAlgorithm: def __init__(self, population_size, mutation_rate, crossover_rate, elitism_rate, tournament_size): self.population_size = population_size self.mutation_rate = mutation_rate self.crossover_rate = crossover_rate self.elitism_rate = elitism_rate self.tournament_size = tournament_size # 初始化种群 def initialize_population(self): population = [] for i in range(self.population_size): x = random.uniform(-10, 10) y = random.uniform(-10, 10) individual = Individual(x, y) population.append(individual) return population # 选择操作 def selection(self, population): selected_population = [] for i in range(self.population_size): tournament = random.sample(population, self.tournament_size) winner = min(tournament, key=lambda x: x.fitness) selected_population.append(winner) return selected_population # 交叉操作 def crossover(self, population): offspring_population = [] for i in range(int(self.population_size * self.crossover_rate)): parent1, parent2 = random.sample(population, 2) offspring_x = (parent1.x + parent2.x) / 2 offspring_y = (parent1.y + parent2.y) / 2 offspring = Individual(offspring_x, offspring_y) offspring_population.append(offspring) return offspring_population # 变异操作 def mutation(self, population): mutated_population = [] for i in range(int(self.population_size * self.mutation_rate)): individual = random.choice(population) mutated_x = individual.x + random.uniform(-0.1, 0.1) mutated_y = individual.y + random.uniform(-0.1, 0.1) mutated_individual = Individual(mutated_x, mutated_y) mutated_population.append(mutated_individual) return mutated_population # 精英保留操作 def elitism(self, population): sorted_population = sorted(population, key=lambda x: x.fitness) elitism_size = int(self.population_size * self.elitism_rate) elitism_population = sorted_population[:elitism_size] return elitism_population # 进化操作 def evolve(self, population): selected_population = self.selection(population) offspring_population = self.crossover(selected_population) mutated_population = self.mutation(offspring_population) new_population = self.elitism(population) + selected_population + mutated_population return new_population # 求解函数最小值 def solve(self): population = self.initialize_population() best_individual = min(population, key=lambda x: x.fitness) for i in range(100): population = self.evolve(population) current_best_individual = min(population, key=lambda x: x.fitness) if current_best_individual.fitness < best_individual.fitness: best_individual = current_best_individual return best_individual.x, best_individual.y # 测试代码 if __name__ == '__main__': ga = GeneticAlgorithm(population_size=100, mutation_rate=0.2, crossover_rate=0.5, elitism_rate=0.1, tournament_size=5) x, y = ga.solve() print(f"The minimum value of the banana function is {banana_function(x, y)} at ({x}, {y})") ``` 在这个示例中,我们使用了一个包含 100 个个体的种群,进行了 100 次迭代,每次迭代使用了 5 轮锦标赛选择,以及 20% 的个体进行变异,50% 的个体进行交叉,和 10% 的精英保留策略。最后输出找到的香蕉函数最小值和对应的 $(x, y)$ 坐标。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值