python实现遗传算法求函数最大值(人工智能作业)

题目:

用遗传算法求函数f(a,b)=2a x sin(8PI x b) + b x cos(13PI x a)最大值,a:[-3,7],b:[-4:10]

实现步骤:

  • 初始化种群
  • 计算种群中每个个体的适应值
  • 淘汰部分个体(这里是求最大值,f值存在正值,所以淘汰所有负值)
  • 轮盘算法对种群进行选择
  • 进行交配、变异,交叉点、变异点随机

分析:

为了方便,先将自变量范围调整为[0,10]、[0,14]
有两个变量,种群中每个个体用一个列表表示,两个列表项,每项是一个二进制字符串(分别由a、b转化而来)
种群之间交配时需要确定交叉点,先将个体染色体中的两个二进制字符串拼接,再确定一个随机数作为交叉点
为了程序的数据每一步都比较清晰正确,我在select、crossover、mutation之后分别都进行了一次适应值的重新计算

具体代码:

import math
import random
def sum(list):
    total = 0.0
    for line in list:
        total += line
    return total
def rand(a, b):
    number =  random.uniform(a,b)
    return math.floor(number*100)/100
PI = math.pi
def fitness(x1,x2):
    return 2*(x1-3)*math.sin(8*PI*x2)+(x2-4)*math.cos(13*PI*x1)
def todecimal(str):
    parta = str[0:4]
    partb = str[4:]
    numerical = int(parta,2)
    partb = partb[::-1]
    for i in range(len(partb)):
        numerical += int(partb[i])*math.pow(0.5,(i+1))
    return numerical
def tobinarystring(numerical):
    numa = math.floor(numerical)
    numb = numerical - numa
    bina =
  • 12
    点赞
  • 109
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
遗传算法是一种常用的优化算法,它可以用来求解函数最大值问题。下面是一个简单的Python实现: ```python import random # 遗传算法求函数最大值 # 目标函数:f(x) = x * sin(10 * pi * x) + 2.0 # 取值范围:-1 <= x <= 2 def fitness(x): return x * math.sin(10 * math.pi * x) + 2.0 def selection(population, fitness): # 选择算子,采用轮盘赌选择 total_fitness = sum(fitness) r = random.uniform(0, total_fitness) for i, f in enumerate(fitness): r -= f if r <= 0: return population[i] def crossover(parent1, parent2): # 交叉算子,采用单点交叉 pos = random.randint(0, len(parent1) - 1) child1 = parent1[:pos] + parent2[pos:] child2 = parent2[:pos] + parent1[pos:] return child1, child2 def mutation(child, mutation_rate): # 变异算子,采用随机突变 for i in range(len(child)): if random.random() < mutation_rate: child[i] = random.uniform(-1, 2) return child # 参数设置 pop_size = 50 # 种群大小 gen_size = 100 # 迭代次数 mutation_rate = 0.01 # 变异概率 # 初始化种群 population = [] for i in range(pop_size): individual = [random.uniform(-1, 2) for j in range(10)] population.append(individual) # 进化 for gen in range(gen_size): # 计算适应度 fitness_list = [fitness(individual) for individual in population] # 选择 new_population = [] for i in range(pop_size): parent1 = selection(population, fitness_list) parent2 = selection(population, fitness_list) child1, child2 = crossover(parent1, parent2) child1 = mutation(child1, mutation_rate) child2 = mutation(child2, mutation_rate) new_population.append(child1) new_population.append(child2) population = new_population # 找出最佳个体 best_individual = max(population, key=fitness) best_fitness = fitness(best_individual) print('best individual:', best_individual) print('best fitness:', best_fitness) ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值