【B++】Python遗传算法代码

import matplotlib.pyplot as plt
import numpy as np
import random

def generate(m, n):  # 出生m个长为n的基因
    return [[random.randint(0, 1) for j in range(n)] for i in range(m)]

def decode(X, max_value, n):  # 解码基因长度为n的个体X
    return eval('0b'+''.join([str(x) for x in X])) / (2**n - 1) * max_value

def decodeAll(A, n):  # 解码基因长度为n的种群A
    return [eval('0b'+''.join([str(x) for x in X])) for X in A]
 
def decode_Y(A, max_value, n):  # 解码基因长度为n的种群A并转换为因变量
    return [f(decode(X, max_value, n)) for X in A]

def filt(obj_value):  # 淘汰(去除负值)
    fit_value = []
    c_min = 0
    for i in range(len(obj_value)):
        if(obj_value[i] + c_min > 0):
            temp = c_min + obj_value[i]
        else:
            temp = 0.0
        fit_value.append(temp)
    return fit_value

def select(fit_value):  # 选择
    total = 0
    for i in range(len(fit_value)):
        total += fit_value[i]
    return total

def selection(pop, fit_value):
    total_fit = select(fit_value) if select(fit_value) else 1
    newfit_value = [i / total_fit for i in fit_value]  # 适应度总和
    # 计算累计概率
    for i in range(len(newfit_value)-2, -1, -1):
        t = 0
        j = 0
        while(j <= i):
            t += newfit_value[j]
            j += 1
            newfit_value[i] = t
            newfit_value[population-1] = 1
    ms = [random.random() for i in range(population)]
    ms.sort()
    fitin = 0
    newin = 0
    newpop = pop
    # 转轮盘选择法
    while newin < population:
        if(ms[newin] < newfit_value[fitin]):
            newpop[newin] = pop[fitin]
            newin += 1
        else:
            fitin += 1
    pop = newpop

def crossover(pop, pc):  # 交叉互换
    for i in range(population-1):
        if(random.random() < pc):
            k = random.randint(0, N)
            pop[i], pop[i+1] = pop[i][:k] + pop[i+1][k:N], pop[i+1][:k] + pop[i][k:N]

def mutation(A, pm):  # 基因突变
    for i in range(population):
        if(random.random() < pm):
            k = random.randint(0, N-1)
            A[i][k] = 1 - A[i][k]

def f(x):  # 目标函数
    try:
        return (np.exp(np.sin(x)))
    except:
        return 0

iter = 1000  # 迭代次数
population = 100 # 种群数量
MAX = 10  # 自变量的最大值
N = 10  # 染色体长度
pc = 0.6   # 互换概率
pm = 0.02   # 变异概率
X, Y = [], []  # 存储每一代的最优解,N个二元组
fit_value = []  # 个体适应度
fit_mean = []  # 平均适应度
# pop = [[0, 1, 0, 1, 0, 1, 0, 1, 0, 1] for i in range(pop_size)]
A = generate(population, N)
for i in range(iter):
    if i%100 == 0:
        print(i)
    obj_value = decode_Y(A, N, MAX)  # 个体评价
    fit_value = filt(obj_value)  # 淘汰
    best = fit_value.index(max(fit_value))
    best_individual, best_fit = A[best], fit_value[best]  # 第一个存储最优的解, 第二个存储最优基因
    X.append(decode(best_individual, MAX, N))
    Y.append(best_fit)
    selection(A, fit_value)  # 新种群复制
    crossover(A, pc)  # 交叉互换
    mutation(A, pm)  # 变异
XY = [(X[i],Y[i]) for i in range(iter)]
XY = sorted(XY, key = lambda x: x[1])
plt.plot(range(iter), XY)
plt.show()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
遗传算法是一种基于生物进化原理的优化算法,用于求解最优化问题。TSP(Traveling Salesman Problem)问题是一个经典的组合优化问题,目标是找到一条最短路径,使得旅行商依次访问所有城市并回到起始城市。 下面是一个使用Python实现遗传算法求解TSP问题的代码示例: ```python import random # 定义城市坐标 cities = { 'A': (0, 0), 'B': (1, 5), 'C': (5, 2), 'D': (3, 6), 'E': (8, 3) } # 遗传算法参数设置 population_size = 50 # 种群大小 elite_size = 10 # 精英个体数量 mutation_rate = 0.01 # 变异率 generations = 100 # 迭代次数 # 计算两个城市之间的距离 def distance(city1, city2): x1, y1 = cities[city1] x2, y2 = cities[city2] return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 # 创建初始种群 def create_individual(): cities_list = list(cities.keys()) random.shuffle(cities_list) return cities_list # 计算个体的适应度(路径长度) def fitness(individual): total_distance = 0 for i in range(len(individual) - 1): total_distance += distance(individual[i], individual[i+1]) total_distance += distance(individual[-1], individual[0]) return total_distance # 选择精英个体 def select_elite(population): population_fitness = [(individual, fitness(individual)) for individual in population] population_fitness.sort(key=lambda x: x[1]) return [individual for individual, _ in population_fitness[:elite_size]] # 交叉操作 def crossover(parent1, parent2): child = [None] * len(parent1) start = random.randint(0, len(parent1) - 1) end = random.randint(start + 1, len(parent1)) child[start:end] = parent1[start:end] for city in parent2: if city not in child: for i in range(len(child)): if child[i] is None: child[i] = city break return child # 变异操作 def mutate(individual): if random.random() < mutation_rate: index1 = random.randint(0, len(individual) - 1) index2 = random.randint(0, len(individual) - 1) individual[index1], individual[index2] = individual[index2], individual[index1] return individual # 遗传算法主函数 def genetic_algorithm(): population = [create_individual() for _ in range(population_size)] for _ in range(generations): elite = select_elite(population) offspring = elite[:] while len(offspring) < population_size: parent1 = random.choice(elite) parent2 = random.choice(elite) child = crossover(parent1, parent2) child = mutate(child) offspring.append(child) population = offspring best_individual = min(population, key=fitness) return best_individual # 执行遗传算法 best_path = genetic_algorithm() best_distance = fitness(best_path) print("最短路径:", best_path) print("最短路径长度:", best_distance) ``` 这段代码实现了一个简单的遗传算法来求解TSP问题。它首先定义了城市坐标和遗传算法的参数,然后实现了计算两个城市之间距离、创建初始种群、计算个体适应度、选择精英个体、交叉操作、变异操作等函数。最后,在遗传算法主函数中执行遗传算法,并输出最优路径和最优路径长度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值