实数编码的遗传算法代码
python遗传算法代码

python遗传算法代码遗传算法是一种基于生物进化原理的优化算法,适用于解决复杂问题。
在Python中,可以使用遗传算法库DEAP (Distributed Evolutionary Algorithms in Python)来实现遗传算法。
DEAP是一个灵活且易于使用的遗传算法框架,提供了用于定义和执行遗传算法的工具。
下面介绍如何使用DEAP库来实现一个简单的遗传算法。
首先,需要安装DEAP库。
可以使用以下命令来安装:```pip install deap```接下来,我们开始编写遗传算法的代码示例。
下面是一个寻找函数f(x)的最小值的例子:```pythonimport randomfrom deap import base, creator, tools# 定义目标函数def f(x):return x**2 + 4*x + 4# 创建遗传算法的环境creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness=creator.FitnessMin)# 初始化遗传算法的参数toolbox = base.Toolbox()toolbox.register("attr_float", random.uniform, -10, 10) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=1)toolbox.register("population", tools.initRepeat, list,toolbox.individual)# 定义评估函数def evaluate(individual):x = individual[0]return f(x),# 定义遗传算法的操作toolbox.register("evaluate", evaluate)toolbox.register("select", tools.selTournament, tournsize=3) toolbox.register("mate", tools.cxTwoPoint)toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.1)# 设置遗传算法的参数population_size = 100n_generations = 100cxpb = 0.5mutpb = 0.2# 创建初始种群population = toolbox.population(n=population_size)# 进化for generation in range(n_generations):offspring = toolbox.select(population, len(population))offspring = [toolbox.clone(ind) for ind in offspring]for child1, child2 in zip(offspring[::2], offspring[1::2]):if random.random() < cxpb:toolbox.mate(child1, child2)del child1.fitness.valuesdel child2.fitness.valuesfor mutant in offspring:if random.random() < mutpb:toolbox.mutate(mutant)del mutant.fitness.valuesinvalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)for ind, fit in zip(invalid_ind, fitnesses):ind.fitness.values = fitpopulation[:] = offspring# 输出最优解best_individual = tools.selBest(population, k=1)[0]best_fitness = evaluate(best_individual)[0]print("Best individual:", best_individual)print("Best fitness:", best_fitness)```在上面的代码中,首先定义了目标函数f(x),然后创建了遗传算法的环境,包括创建适应度函数和个体类,以及注册遗传算法的操作。
遗传算法代码python

遗传算法代码python一、简介遗传算法是一种通过模拟自然选择和遗传学原理来寻找最优解的优化算法。
它广泛应用于各种领域,包括优化问题、搜索和机器学习等。
二、代码概述以下是一个简单的遗传算法的Python代码示例,用于解决简单的优化问题。
该算法使用一个简单的二进制编码方式,并使用适应度函数来评估每个个体的适应度。
三、代码实现```pythonimportnumpyasnp#遗传算法参数POPULATION_SIZE=100#种群规模CROSSOVER_RATE=0.8#交叉概率MUTATION_RATE=0.1#变异概率MAX_GENERATIONS=100#最大迭代次数#适应度函数deffitness(individual):#在这里定义适应度函数,评估每个个体的适应度#这里简单地返回个体值的平方,可以根据实际问题进行调整returnnp.sum(individual**2)#初始种群生成pop=np.random.randint(2,size=(POPULATION_SIZE,))#迭代过程forgenerationinrange(MAX_GENERATIONS):#评估种群中每个个体的适应度fitness_values=np.apply_along_axis(fitness,1,pop)#选择种群selected_idx=np.random.choice(np.arange(POPULATION_SIZE), size=POPULATION_SIZE,replace=True,p=fitness_values/fitness_va lues.sum())selected_pop=pop[selected_idx]#交叉操作ifCROSSOVER_RATE>np.random.rand():cross_points=np.random.rand(POPULATION_SIZE,2)<0.5#随机选择交叉点cross_pop=np.array([np.hstack((individual[cross_points[i, 0]:cross_points[i,1]]+individual[cross_points[i,1]:],other))f ori,otherinenumerate(selected_pop)]).T#合并个体并随机交叉得到新的个体cross_pop=cross_pop[cross_points]#将交叉后的个体重新排列成原始种群大小selected_pop=np.vstack((selected_pop,cross_pop))#将新个体加入种群中#变异操作ifMUTATION_RATE>np.random.rand():mutated_pop=selected_pop+np.random.randn(POPULATION_SIZE, 1)*np.sqrt(np.log(POPULATION_SIZE))*(selected_pop!=pop).astyp e(np.float)#根据变异概率对个体进行变异操作,得到新的个体种群mutated_pop=mutated_pop[mutated_pop!=0]#将二进制种群中值为0的个体去掉,因为这些个体是随机的二进制串,不是解的一部分,不应该参与变异操作selected_pop=mutated_pop[:POPULATION_SIZE]#将新种群中除最后一个以外的部分加入原始种群中(即新的种群被排除了适应度最差的个体)#选择当前最好的个体(用于更新最优解)best_idx=np.argmax(fitness_values)best_solution=selected_pop[best_idx]print(f"Generation{generation}:Bestsolution:{best_solutio n}")```四、使用示例假设要解决一个简单的优化问题:求一个一维函数的最小值。
python遗传算法代码

python遗传算法代码遗传算法是一种模拟生物进化过程的优化算法,常用于解决复杂的优化问题。
Python是一种简单易用且功能强大的编程语言,非常适合实现遗传算法。
下面是一个简单的Python遗传算法代码示例,用于求解一个二进制字符串中最长连续1的长度。
```pythonimport random# 设置遗传算法的参数POPULATION_SIZE = 100 # 种群大小GENERATION_COUNT = 50 # 迭代次数MUTATION_RATE = 0.01 # 变异率# 初始化种群def initialize_population():population = []for i in range(POPULATION_SIZE):individual = []for j in range(10): # 假设二进制字符串长度为10gene = random.randint(0, 1)individual.append(gene)population.append(individual)return population# 计算适应度def calculate_fitness(individual):fitness = 0current_streak = 0for gene in individual:if gene == 1:current_streak += 1fitness = max(fitness, current_streak)else:current_streak = 0return fitness# 选择操作:轮盘赌选择def selection(population):total_fitness = sum([calculate_fitness(individual) for individual in population])probabilities = [calculate_fitness(individual) /total_fitness for individual in population]selected_population = []for _ in range(POPULATION_SIZE):selected_individual = random.choices(population, weights=probabilities)[0]selected_population.append(selected_individual)return selected_population# 交叉操作:单点交叉def crossover(parent1, parent2):point = random.randint(1, len(parent1) - 1)child1 = parent1[:point] + parent2[point:]child2 = parent2[:point] + parent1[point:]return child1, child2# 变异操作def mutation(individual):for i in range(len(individual)):if random.random() < MUTATION_RATE:individual[i] = 1 - individual[i] # 变异位点翻转return individual# 主函数def genetic_algorithm():population = initialize_population()for _ in range(GENERATION_COUNT):population = selection(population)# 交叉操作new_population = []for i in range(0, POPULATION_SIZE, 2):parent1 = population[i]parent2 = population[i + 1]child1, child2 = crossover(parent1, parent2)new_population.append(child1)new_population.append(child2)# 变异操作population = [mutation(individual) for individual in new_population]best_individual = max(population, key=calculate_fitness) return best_individual# 运行遗传算法best_individual = genetic_algorithm()best_fitness = calculate_fitness(best_individual)print('Best individual:', best_individual)print('Best fitness:', best_fitness)```该代码首先初始化一个种群,然后通过选择、交叉和变异操作迭代地更新种群,并最终返回适应度最高的个体。
【智能算法】超详细的遗传算法(GeneticAlgorithm)解析和TSP求解代码详解

回到3.1中提的求一元函数最大值的问题。在上面我们把极大值比喻为山峰,那么,袋鼠的位置坐标可以比喻为区间[-1, 2]的某一个x坐标 (有了x坐标,再通过函数表达式可以算出函数值 <==> 得到了袋鼠染色体编码,解码得到位置坐标,在喜马拉雅山脉地图查询位置坐标算 出海拔高度)。这个x坐标是一个实数,现在,说白了就是怎么对这个x坐标进行编码。下面我们以二进制编码为例讲解,不过这种情况下以 二进制编码比较复杂就是了。(如果以浮点数编码,其实就很简洁了,就一浮点数而已。)
就像0和1两种碱基,然后将他们串成一条链形成染色体。一个位能表示出2种 状态的信息量,因此足够长的二进制染色体便能表示所有的特征。这便是二进制编码。如下:
1110001010111
它由二进制符号0和1所组成的二值符号集。它有以下一些优点:
image 当指针在这个转盘上转动,停止下来时指向的个体就是天选之人啦。可以看出,适应性越高的个体被选中的概率就越大。
遗传算法的交叉操作,是指对两个相互配对的染色体按某种方式相互交换其部分基因,从而形成两个新的个体。 适用于二进制编码个体或浮点数编码个体的交叉算子: 1. 单点交叉(One-point Crossover):指在个体编码串中只随机设置一个交叉点,然后再该点相互交换两个配对个体的部分染色体。 2. 两点交叉与多点交叉:
(1) 两点交叉(Two-point Crossover):在个体编码串中随机设置了两个交叉点,然后再进行部分基因交换。 (2) 多点交叉(Multi-point Crossover) 3. 均匀交叉(也称一致交叉,Uniform Crossover):两个配对个体的每个基因座上的基因都以相同的交叉概率进行交换,从而形成两 个新个体。 4. 算术交叉(Arithmetic Crossover):由两个个体的线性组合而产生出两个新的个体。该操作对象一般是由浮点数编码表示的个体。 咳咳,根据国际惯例。还是抓一个最简单的二进制单点交叉为例来给大家讲解讲解。 二进制编码的染色体交叉过程非常类似高中生物中所讲的同源染色体的联会过程――随机把其中几个位于同一位置的编码进行交换,产生新 的个体。
实值编码遗传算法源程序

*/
/* input file `gadata.txt '. It randomly generates values */
/* between these bounds for each gene of each genotype in the */
void initialize(void);
double randval(double,double);
void evaluate(void);
void keep_the_best(void);
void elitist(void);
void select(void);
{
double gene[NVARS]; /* 个体基因串 */
double fitness; /* 个体适应度 */
double upper[NVARS]; /* 个体参数上限 */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define POPSIZE 50 /* 群体规模 */
population[j].fitness=0;
population[j].rfitness=0;
population[j].cfitness=0;
population[j].lower[i]=lbound;
population[j].upper[i]=ubound;
population[j].gene[i]=randval(population[j].lower[i],
基于实数编码的参数自适应遗传算法(matlab代码)

基于实数编码的参数⾃适应遗传算法(matlab代码)实数编码的遗传算法寻优:遗传算法的基本操作算⼦:(1)选择算⼦选择算⼦的作⽤主要是避免优良基因的丢失,使得性能⾼的个体能以更⼤的概率被选中,有机会作为⽗代繁殖下⼀代,从⽽提⾼遗传算法的全局收敛性及计算效率。
常见的选择算⼦包括轮盘赌选择法、随机遍历抽样法、局部选择法及锦标赛选择法等。
选择算⼦采⽤轮盘赌;(2)交叉算⼦在遗传算法中,交叉算⼦是区别于其它优化算法的本质特征,⽤于组合新的个体在解空间中快速有效地进⾏搜索,同时也降低了对有效模式的破坏程度,起到全局搜索寻优的效果。
交叉算⼦直接影响着遗传算法的最终搜索效果,⼀定程度上决定了其发展前景。
其中alpha为参数,0<alpha<1(3)变异算⼦群体基因的多样性是保证遗传算法寻找到全局最优解的前提条件,然⽽在进化过程中,遗传选择操作削弱了群体的多样性,上述交叉算⼦只有满⾜⼀定的条件才能保持群体的多样性,⽽变异操作则是保持群体多样性的有效算⼦,所以变异操作算⼦的选取也是必不可少的。
变异尺度⾃适应变化的变异算⼦在进化初期采⽤较⼤的变异尺度来保持群体的多样性,⽽在后期变异尺度将逐渐缩⼩以提⾼局部微调能⼒。
本⽂在此基础上做些改进,改进后的变异算⼦具有原有算⼦的优点,且操作上⽐原有算⼦简单⽅便,有效地加快遗传算法的收敛速度,具体如下:可以看出s(t) 决定了变异空间的⼤⼩,在迭代的初期,变异空间较⼤,在迭代的后期,变异空间缩⼩,算法的局部寻优能⼒变强。
变异算⼦参考⽂献: [1] 管⼩艳. 实数编码下遗传算法的改进及其应⽤[D].重庆⼤学,2012.参数⾃适应:交叉概率Pc和变异概率Pm是遗传算法的两个重要的参数,这两个参数决定了每个个体进⾏交叉或者变异操作的概率。
⾃适应算⼦参考⽂献:[2] M. Srinivas and L. M. Patnaik, "Adaptive probabilities of crossover and mutation in genetic algorithms," in IEEE Transactions on Systems, Man, and Cybernetics, vol. 24, no. 4, pp. 656-667, April 1994.doi: 10.1109/21.286385上述部分翻译⾃⽂献[2]按照论⽂描述,对算法的复现如下:% 测试函数图像% 测试函数图像% 改进的⾃适应遗传算法:% 参考⽂献:[7] M. Srinivas and L. M. Patnaik, "Adaptive probabilities of crossover and mutation in genetic algorithms,"% in IEEE Transactions on Systems, Man, and Cybernetics, vol. 24, no. 4, pp. 656-667, April 1994.% doi: 10.1109/21.286385clc;clear all;mode = 'Schaffer';% mode = 'self_define';if strcmp(mode, 'Schaffer')figure(1)x = -4:0.1:4;y = -4:0.1:4;[X,Y] = meshgrid(x,y);% Z = 3*cos(X.*Y)+X+Y.^2;Z = 0.5-((sin(sqrt(X.^2+Y.^2)).^2)-0.5)./(1+0.001.*(X.^2+Y.^2)).^2; surf(X,Y,Z);title('Schaffer Function');xlabel('X-轴');ylabel('Y-轴');zlabel('Z-轴');figure(2);contour(X, Y, Z, 8);title('Schaffer函数等⾼线');xlabel('X-轴');ylabel('Y-轴');endif strcmp(mode, 'self_define')figure(1);x = -4:0.1:4;y = -4:0.1:4;[X,Y] = meshgrid(x,y);% Z = 100.*(Y-X.^2).^2+(1-X).^2;Z = (cos(X.^2+Y.^2)-0.1)./(1+0.3*(X.^2+Y.^2).^2)+3;surf(X,Y,Z);%title('Rosen Brock valley Function');title('Self define Function');xlabel('X-轴');ylabel('Y-轴');zlabel('Z-轴');endclc;clearvars -except mode;r = 0.2;b = 3;NP=400;% Pc=0.65; % 将Pc,Pm参数改进为⾃适应参数% Pm=0.20;G=520; % 记得改D=2; % 变量个数k1 = 1;k3 = 1;k2 = 0.5;k4 = 0.5;X_min=-4;X_max=4;Y_min=-4;Y_max=4;% optimization_trace = []; % 三维数组, ⾏,列,叶for count_1=1:NP % 产⽣初始解temp1 = X_min+rand()*(X_max-X_min);temp2 = Y_min+rand()*(Y_max-Y_min);x(count_1,:) = [temp1,temp2];endsave_pic_cnt = 1;A = figure(3);for gen=1:G%pause(0.2);if rem(gen, 100)==1scatter(x(:,1), x(:, 2));axis([-4, 4, -4, 4]);title(['第', num2str(gen), '次迭代']);xlabel('变量X');ylabel('变量Y');base_path = 'C:\Users\18811\Desktop\graph\';cnt = num2str(save_pic_cnt);tail_path = '.jpg';frame = getframe(A);im=frame2im(frame);path_img = [base_path, cnt, tail_path];% imwrite(im, path_img);% save_x(:, :, save_pic_cnt) = x;save_pic_cnt = save_pic_cnt + 1;% scatter(0, 0, 'o', 'r');for count_2=1:NPfitness(count_2)=func(x(count_2,:), mode);end%[fitness_min,index0] = min(fitness);%fitness_max = max(fitness);[fitness_max,index0] = max(fitness);fitness_average = sum(fitness)/(length(fitness)); % 种群的平均值collect_fit_average(gen) = fitness_average; % 保存适应度的平均值collect_fitmax_subtract_fit_average(gen) = fitness_max - fitness_average; % 保存f_max-f_average ;fitness_min = min(fitness);best_indiv = x(index0,:); % 最优的个体% optimization_trace(gen,: , global_count) = best_indiv;% best_solution(gen) = fitness_min;best_solution(gen) = fitness_max;% 计算归⼀化的适应度值fitness = (fitness - fitness_min)/(fitness_max - fitness_min);fitness_sum = sum(fitness);fitness = fitness./fitness_sum;fitness = cumsum(fitness);% 选择算⼦:ms = sort(rand(NP,1));fiti = 1;newi = 1;while newi<=NPif ms(newi)<fitness(fiti)clone_x(newi,:) = x(newi,:);newi = newi + 1;elsefiti = fiti + 1;endendclone_x = clone_x(1:NP, :);% 进⾏交叉,变异操作% count=0;for count=1:2:NP% ⾃适应计算Pc.% 选区两个交叉的个体的较⼤的适应度值if fitness(count)>=fitness(count+1)fitness_selected = fitness(count);elsefitness_selected = fitness(count+1);end% 计算Pcif fitness_selected >= fitness_averagePc = k1*(fitness_max-fitness_selected)/(fitness_max-fitness_average);elsePc = k3;endcollect_Pc(gen, count) = Pc; % 保存Pc的值temp_cross = rand();if temp_cross < Pc% 交叉算⼦注:这种交叉算⼦效果更好temp_alpha = 0.6;cross_x(count,:) = temp_alpha*clone_x(count,:)+(1-temp_alpha)*clone_x(count+1,:);cross_x(count+1,:) = temp_alpha*clone_x(count+1,:)+(1-temp_alpha)*clone_x(count,:);% 改进的交叉算⼦参考⽂献:管⼩艳. 实数编码下遗传算法的改进及其应⽤[D].重庆⼤学,2012. 注:但这种交叉算⼦实际的效果不理想% temp_gama = rand();% temp_alpha = 0.98;% cross_x(count,:) = temp_alpha*clone_x(count,:)+(1-temp_alpha)*clone_x(count+1,:)+temp_gama*(clone_x(count,:)-clone_x(count+1,:)); % cross_x(count+1,:) = temp_alpha*clone_x(count+1,:)+(1-temp_alpha)*clone_x(count,:)+temp_gama*(clone_x(count,:)-clone_x(count+1,:)); elsecross_x(count,:)=clone_x(count,:);cross_x(count+1,:)=clone_x(count+1,:);end% 边界条件检查if cross_x(count,1)>X_max || cross_x(count,1)<X_min || cross_x(count,2)>Y_max || cross_x(count,2)<Y_mintemp1 = X_min+rand()*(X_max-X_min);temp2 = Y_min+rand()*(Y_max-Y_min);cross_x(count,:) = [temp1,temp2];endendcross_x = cross_x(1:NP,:);% cross_x为完成交叉的个体;% 变异操作for count=1:1:NP% 计算Pmif fitness(count)>=fitness_averagePm = k2*(fitness_max-fitness(count))/(fitness_max-fitness_average);elsePm = k4;collect_Pm(gen,count) = Pm; % 保存Pm的值temp_mutation=rand();if temp_mutation<Pm%mutation_x(count,:) = (1+0.01).*cross_x(count,:); %这种变异算⼦效果不理想% 变异算⼦参考⽂献:管⼩艳. 实数编码下遗传算法的改进及其应⽤[D].重庆⼤学,2012mutation_pos = randi(D);if mutation_pos==1low = X_min;high = X_max;elselow = Y_min;high = Y_max;ends_t(gen) = 1-r^((1-gen/G)^b);new_low = cross_x(count, mutation_pos)-s_t(gen)*(cross_x(count, mutation_pos)-low);new_high = cross_x(count, mutation_pos)+s_t(gen)*(high-cross_x(count, mutation_pos));mutation_x(count, :) = cross_x(count, :);mutation_x(count, mutation_pos) = new_low+rand()*(new_high-new_low);if mutation_x(count,1)>X_max || mutation_x(count,1)<X_min || mutation_x(count,2)>Y_max || mutation_x(count,2)<Y_min temp1 = X_min+rand()*(X_max-X_min);temp2 = Y_min+rand()*(Y_max-Y_min);mutation_x(count,:) = [temp1,temp2];endelsemutation_x(count,:) = cross_x(count,:);endend%边界条件处理x=mutation_x(1:NP, :);x(1,:)= best_indiv;end%% 作图figure(4)plot(best_solution);%hold on;xlabel('进化代数');ylabel('适应度值');title('适应度进化曲线');figure(5);plot(collect_fitmax_subtract_fit_average);title('f_{max}-f_{average}曲线');xlabel('进化代数');ylabel('f_{max}-f_{average}');% function f=func(buf)% f=0.5-((sin(sqrt(buf(1).^2+buf(2).^2)).^2)-0.5)./(1+0.001.*(buf(1).^2+buf(2).^2)).^2;% endfunction f=func(buf, md)if strcmp(md, 'Schaffer')f=0.5-((sin(sqrt(buf(1).^2+buf(2).^2)).^2)-0.5)./(1+0.001.*(buf(1).^2+buf(2).^2)).^2;endif strcmp(md,'self_define')% f = 100*(buf(2)-buf(1).^2).^2+(1-buf(1)).^2;f = (cos(buf(1).^2+buf(2).^2)-0.1)./(1+0.3*(buf(1).^2+buf(2).^2).^2)+3;endend测试函数:Schaffer函数:运⾏结果:种群的分布变化:-----------------------------------------------------分割线----------------------------------------------------2019/4/2 上⾯的代码有两个地⽅写错了,现在已经改正:1. ⽤于轮盘赌的fitness应该与⽤于计算⾃适应参数的fitness分开2.对轮盘赌选择算⼦进⾏修改修改后的代码:% 测试函数图像% 测试函数图像% 改进的⾃适应遗传算法:% 参考⽂献:[7] M. Srinivas and L. M. Patnaik, "Adaptive probabilities of crossover and mutation in genetic algorithms," % in IEEE Transactions on Systems, Man, and Cybernetics, vol. 24, no. 4, pp. 656-667, April 1994.% doi: 10.1109/21.286385clc;clear all;mode = 'Schaffer';% mode = 'self_define';if strcmp(mode, 'Schaffer')figure(1)x = -4:0.1:4;y = -4:0.1:4;[X,Y] = meshgrid(x,y);% Z = 3*cos(X.*Y)+X+Y.^2;Z = 0.5-((sin(sqrt(X.^2+Y.^2)).^2)-0.5)./(1+0.001.*(X.^2+Y.^2)).^2;surf(X,Y,Z);title('Schaffer Function');xlabel('X-轴');ylabel('Y-轴');zlabel('Z-轴');figure(2);contour(X, Y, Z, 8);title('Schaffer函数等⾼线');xlabel('X-轴');ylabel('Y-轴');endif strcmp(mode, 'self_define')figure(1);x = -4:0.1:4;y = -4:0.1:4;[X,Y] = meshgrid(x,y);% Z = 100.*(Y-X.^2).^2+(1-X).^2;Z = (cos(X.^2+Y.^2)-0.1)./(1+0.3*(X.^2+Y.^2).^2)+3;surf(X,Y,Z);%title('Rosen Brock valley Function');title('Self define Function');xlabel('X-轴');ylabel('Y-轴');zlabel('Z-轴');endclc;clearvars -except mode;r = 0.2;b = 3;NP=100;% Pc=0.65; % 将Pc,Pm参数改进为⾃适应参数% Pm=0.20;G=100; % 记得改D=2; % 变量个数k1 = 1;k3 = 1;k2 = 0.5;k4 = 0.5;X_min=-4;X_max=4;Y_min=-4;Y_max=4;% optimization_trace = []; % 三维数组, ⾏,列,叶for count_1=1:NP % 产⽣初始解temp1 = X_min+rand()*(X_max-X_min);temp2 = Y_min+rand()*(Y_max-Y_min);x(count_1,:) = [temp1,temp2];endsave_pic_cnt = 1;A = figure(3);for gen=1:Gpause(0.2);if rem(gen, 2)==1scatter(x(:,1), x(:, 2));axis([-4, 4, -4, 4]);title(['第', num2str(gen), '次迭代']);xlabel('变量X');ylabel('变量Y');base_path = 'C:\Users\18811\Desktop\graph\';cnt = num2str(save_pic_cnt);tail_path = '.jpg';frame = getframe(A);im=frame2im(frame);path_img = [base_path, cnt, tail_path];% imwrite(im, path_img);% save_x(:, :, save_pic_cnt) = x;save_pic_cnt = save_pic_cnt + 1;end% scatter(0, 0, 'o', 'r');for count_2=1:NPfitness(count_2)=func(x(count_2,:), mode);endfitness_ = fitness;%[fitness_min,index0] = min(fitness);%fitness_max = max(fitness);[fitness_max,index0] = max(fitness);fitness_average = sum(fitness)/(length(fitness)); % 种群的平均值collect_fit_average(gen) = fitness_average; % 保存适应度的平均值collect_fitmax_subtract_fit_average(gen) = fitness_max - fitness_average; % 保存f_max-f_average ; fitness_min = min(fitness);best_indiv = x(index0,:); % 最优的个体% optimization_trace(gen,: , global_count) = best_indiv;% best_solution(gen) = fitness_min;best_solution(gen) = fitness_max;% 计算归⼀化的适应度值fitness = (fitness - fitness_min)/(fitness_max - fitness_min);fitness_sum = sum(fitness);fitness = fitness./fitness_sum;fitness = cumsum(fitness);% 轮盘赌选择newi = 1;while newi<=NPrandom_num = rand(); % ⽣成随机数if random_num<fitness(1)clone_x(newi, :) = x(1, :);newi = newi+1;elsefor ct=1:NP-1if random_num>fitness(ct) && random_num<fitness(ct+1)clone_x(newi,:) = x(ct,:);newi = newi+1;break;endendendend% disp(clone_x - x);% 进⾏交叉,变异操作% count=0;for count=1:2:NP% ⾃适应计算Pc.% 选区两个交叉的个体的较⼤的适应度值if fitness_(count)>=fitness_(count+1)fitness_selected = fitness_(count);elsefitness_selected = fitness_(count+1);end% 计算Pcif fitness_selected >= fitness_averagePc = k1*(fitness_max-fitness_selected)/(fitness_max-fitness_average);elsePc = k3;endcollect_Pc(gen, count) = Pc; % 保存Pc的值temp_cross = rand();if temp_cross < Pc% 交叉算⼦注:这种交叉算⼦效果更好temp_alpha = 0.6;cross_x(count,:) = temp_alpha*clone_x(count,:)+(1-temp_alpha)*clone_x(count+1,:);cross_x(count+1,:) = temp_alpha*clone_x(count+1,:)+(1-temp_alpha)*clone_x(count,:);% 改进的交叉算⼦参考⽂献:管⼩艳. 实数编码下遗传算法的改进及其应⽤[D].重庆⼤学,2012. 注:但这种交叉算⼦实际的效果不理想% temp_gama = rand();% temp_alpha = 0.98;% cross_x(count,:) = temp_alpha*clone_x(count,:)+(1-temp_alpha)*clone_x(count+1,:)+temp_gama*(clone_x(count,:)-clone_x(count+1,:)); % cross_x(count+1,:) = temp_alpha*clone_x(count+1,:)+(1-temp_alpha)*clone_x(count,:)+temp_gama*(clone_x(count,:)-clone_x(count+1,:)); elsecross_x(count,:)=clone_x(count,:);cross_x(count+1,:)=clone_x(count+1,:);end% 边界条件检查if cross_x(count,1)>X_max || cross_x(count,1)<X_min || cross_x(count,2)>Y_max || cross_x(count,2)<Y_mintemp1 = X_min+rand()*(X_max-X_min);temp2 = Y_min+rand()*(Y_max-Y_min);cross_x(count,:) = [temp1,temp2];endendcross_x = cross_x(1:NP,:);% cross_x为完成交叉的个体;% 变异操作for count=1:1:NP% 计算Pmif fitness_(count)>=fitness_averagePm = k2*(fitness_max-fitness_(count))/(fitness_max-fitness_average);elsePm = k4;endcollect_Pm(gen,count) = Pm; % 保存Pm的值temp_mutation=rand();if temp_mutation<Pm%mutation_x(count,:) = (1+0.01).*cross_x(count,:); %这种变异算⼦效果不理想% 变异算⼦参考⽂献:管⼩艳. 实数编码下遗传算法的改进及其应⽤[D].重庆⼤学,2012mutation_pos = randi(D);if mutation_pos==1low = X_min;high = X_max;elselow = Y_min;high = Y_max;ends_t(gen) = 1-r^((1-gen/G)^b);new_low = cross_x(count, mutation_pos)-s_t(gen)*(cross_x(count, mutation_pos)-low);new_high = cross_x(count, mutation_pos)+s_t(gen)*(high-cross_x(count, mutation_pos));mutation_x(count, :) = cross_x(count, :);mutation_x(count, mutation_pos) = new_low+rand()*(new_high-new_low);if mutation_x(count,1)>X_max || mutation_x(count,1)<X_min || mutation_x(count,2)>Y_max || mutation_x(count,2)<Y_mintemp1 = X_min+rand()*(X_max-X_min);temp2 = Y_min+rand()*(Y_max-Y_min);mutation_x(count,:) = [temp1,temp2];endelsemutation_x(count,:) = cross_x(count,:);endend%边界条件处理x=mutation_x(1:NP, :);x(1,:)= best_indiv;end%% 作图figure(4)plot(best_solution);%hold on;xlabel('进化代数');ylabel('适应度值');title('适应度进化曲线');figure(5);plot(collect_fitmax_subtract_fit_average);title('f_{max}-f_{average}曲线');xlabel('进化代数');ylabel('f_{max}-f_{average}');% function f=func(buf)% f=0.5-((sin(sqrt(buf(1).^2+buf(2).^2)).^2)-0.5)./(1+0.001.*(buf(1).^2+buf(2).^2)).^2; % endfunction f=func(buf, md)if strcmp(md, 'Schaffer')f=0.5-((sin(sqrt(buf(1).^2+buf(2).^2)).^2)-0.5)./(1+0.001.*(buf(1).^2+buf(2).^2)).^2; endif strcmp(md,'self_define')% f = 100*(buf(2)-buf(1).^2).^2+(1-buf(1)).^2;f = (cos(buf(1).^2+buf(2).^2)-0.1)./(1+0.3*(buf(1).^2+buf(2).^2).^2)+3;endend修改后的算法寻优效果得到很⼤的提升,⾮常感谢指出代码中的错误:运⾏结果:。
(完整版)遗传算法c语言代码

srand((unsigned)time(NULL));
for(i=0;i<num;i++)
{
bianyip[i]=(rand()%100);
bianyip[i]/=100;
}
//确定可以变异的染色体
t=0;
for(i=0;i<num;i++)
{
if(bianyip[i]<pm)
printf("\n******************是否想再一次计算(y or n)***********************\n");
fflush(stdin);
scanf("%c",&choice);
}while(choice=='y');
return 0;
}
{
flag=0;
break;
}
}
if(flag)
{
group[i].city[j]=t;
j++;
}
}
}
printf("************初始种群如下****************\n");
for(i=0;i<num;i++)
{
for(j=0;j<cities;j++)
printf("%4d",group[i].city[j]);
{
group[i].p=1-(double)group[i].adapt/(double)biggestsum;
biggestp+=group[i].p;
遗传算法经典MATLAB代码

遗传算法经典学习Matlab代码遗传算法实例:也是自己找来的,原代码有少许错误,本人都已更正了,调试运行都通过了的。
对于初学者,尤其是还没有编程经验的非常有用的一个文件遗传算法实例% 下面举例说明遗传算法%% 求下列函数的最大值%% f(x)=10*sin(5x)+7*cos(4x) x∈[0,10]%% 将x 的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为(10-0)/(2^10-1)≈0.01。
%% 将变量域[0,10] 离散化为二值域[0,1023], x=0+10*b/1023, 其中 b 是[0,1023] 中的一个二值数。
%% %%--------------------------------------------------------------------------------------------------------------%%--------------------------------------------------------------------------------------------------------------%% 编程%-----------------------------------------------% 2.1初始化(编码)% initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度),% 长度大小取决于变量的二进制编码的长度(在本例中取10位)。
%遗传算法子程序%Name: initpop.m%初始化function pop=initpop(popsize,chromlength)pop=round(rand(popsize,chromlength)); % rand随机产生每个单元为{0,1} 行数为popsize,列数为chromlength的矩阵,% roud对矩阵的每个单元进行圆整。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
function GA_real_coded_min
% ±¾ÀýΪʵÊý±àÂëÒÅ´«Ëã·¨Çóº¯Êý×îСֵµÄÓÅ»¯ÎÊÌâ
% Ä¿±êº¯ÊýΪ J = x1^2 + x2^2
% ÆäÖÐ x1 µÄ·¶Î§Îª [-10,10], x2 µÄ·¶Î§Îª [-10,10]
Size = 200;% the value of population
CodeL = 2;
MinX(1) = -10;
MaxX(1) = 10;
MinX(2) = -10;
MaxX(2) = 10;
E(:,1) = MinX(1) + (MaxX(1)-MinX(1))*rand(Size,1);
E(:,2) = MinX(2) + (MaxX(2)-MinX(2))*rand(Size,1);
G = 100;% the max generation
%---------------Start
Running---------------------------------------------
for kg = 1 : G
time(kg) = kg;
%----------------------step 1: Evaluate BestJ-------------------------for i = 1 : Size
xi = E(i,:);
x1 = xi(1);
x2 = xi(2);
% ÏÂÃæµÄ F
ÓÃÓÚ¼ÆËã¸öÌåµÄÊÊÓ¦¶ÈÖµ£¬ÊÊÓ¦¶Èº¯Êý¸ù¾ÝÄ¿±êº¯Êý½øÐÐÁËÏßÐԱ任
F(i) = 1/(x1^2 + x2^2);% ¼ÆËãÊÊÓ¦¶ÈÖµ£¬Ô½´óÔ½ºÃ
Ji = x1^2 + x2^2;% ¼ÆËãÄ¿±êÖµ£¬Ô½Ð¡Ô½ºÃ
BsJi(i) = min(Ji);
end
[OrderJi,IndexJi] = sort(BsJi);
BestJ(kg) = OrderJi(1);
Ji = BsJi + eps;% Avoiding deviding zero
fi = F;
[Orderfi,Indexfi] = sort(fi); % Arranging fi small to bigger
Bestfi = Orderfi(Size); % Let Bestfi=max(fi)
BestS = E(Indexfi(Size),:); % Let BestS=E(m),m is the Indexfi belongs to max(fi)
bfi(kg) = Bestfi;
kg
BestS
%--------------------Step 2:Select and Reproduct Operation------------ fi_sum = sum(fi);
fi_Size = (Orderfi/fi_sum)*Size;
fi_S = floor(fi_Size); % Selecting Bigger fi value
r = Size - sum(fi_S);
Rest = fi_Size - fi_S;
[RestValue,Index] = sort(Rest);
for i = Size : -1 : Size-r+1
fi_S(Index(i)) = fi_S(Index(i)) + 1;% Adding rest to equal Size end
k = 1;
for i = Size : -1 : 1
for j = 1 : fi_S(i)
TempE(k,:) = E(Indexfi(i),:); % Selecting and Reproduce
k = k + 1; % k is used to reproduce end
end
%---------------------Step 3: Crossover Operation--------------------- Pc = 0.90;
for i = 1 : 2 : Size-1
temp = rand;
if Pc > temp
alfa = rand;
TempE(i,:) = alfa*E(i+1,:) + (1-alfa)*E(i,:);
TempE(i+1,:) = alfa*E(i,:) + (1-alfa)*E(i+1,:);
end
end
TempE(Size,:) = BestS;
E = TempE;
%---------------------Step 4: Mutation Operation---------------------- Pm = 0.10 - [1:Size]*(0.01)/Size; % Bigger fi,smaller Pm
Pm_rand = rand(Size,CodeL);
Mean = (MaxX+MinX)/2;
Dif = MaxX - MinX;
for i = 1 : Size
for j = 1 : CodeL
if Pm(i) > Pm_rand(i,j);
TempE(i,j) = Mean(j) + Dif(j)*(rand-0.5);
end
end
end
% Guarantee TempE(Size,:) belong to the best individual
TempE(Size,:) = BestS;
E = TempE;
end
%-------------------------------------------------------------------------
BestS
Bestfi
figure(1);
plot(time,BestJ,'b');
xlabel('Generations'); ylabel('Best Objective');% the value of objective figure(2);
plot(time,bfi,'b');
xlabel('Generations'); ylabel('Best Fitness');% the value of fitness。