实数编码的遗传算法代码
- 格式:docx
- 大小:15.90 KB
- 文档页数:2
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代码示例,用于解决简单的优化问题。
该算法使用一个简单的二进制编码方式,并使用适应度函数来评估每个个体的适应度。
三、代码实现```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遗传算法代码示例,用于求解一个二进制字符串中最长连续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)```该代码首先初始化一个种群,然后通过选择、交叉和变异操作迭代地更新种群,并最终返回适应度最高的个体。
基于实数编码的参数⾃适应遗传算法(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修改后的算法寻优效果得到很⼤的提升,⾮常感谢指出代码中的错误:运⾏结果:。
遗传算法经典学习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对矩阵的每个单元进行圆整。
以下是一个简单的遗传算法的C语言代码示例:c#include <stdio.h>#include <stdlib.h>#include <time.h>#include <math.h>#define POPULATION_SIZE 100#define GENE_LENGTH 10#define MAX_GENERATIONS 1000#define MUTATION_RATE 0.01#define CROSSOVER_RATE 0.8typedef struct Individual {char genes[GENE_LENGTH];double fitness;} Individual;double calculate_fitness(Individual* individual) {// 计算适应度函数,这里使用简单的二进制字符串中1的个数作为适应度 int count = 0;for (int i = 0; i < GENE_LENGTH; i++) {if (individual->genes[i] == '1') {count++;}}return count;}void initialize_population(Individual* population) {// 初始化种群for (int i = 0; i < POPULATION_SIZE; i++) {for (int j = 0; j < GENE_LENGTH; j++) {population[i].genes[j] = rand() % 2 ? '0' : '1';}population[i].fitness = calculate_fitness(&population[i]); }}void selection(Individual* population, Individual* parents) {// 选择操作,采用轮盘赌算法选择两个父代个体double total_fitness = 0;for (int i = 0; i < POPULATION_SIZE; i++) {total_fitness += population[i].fitness;}double rand1 = rand() / (double)RAND_MAX * total_fitness;double rand2 = rand() / (double)RAND_MAX * total_fitness;double cumulative_fitness = 0;int parent1_index = -1, parent2_index = -1;for (int i = 0; i < POPULATION_SIZE; i++) {cumulative_fitness += population[i].fitness;if (rand1 < cumulative_fitness && parent1_index == -1) {parent1_index = i;}if (rand2 < cumulative_fitness && parent2_index == -1) {parent2_index = i;}}parents[0] = population[parent1_index];parents[1] = population[parent2_index];}void crossover(Individual* parents, Individual* offspring) {// 交叉操作,采用单点交叉算法生成两个子代个体int crossover_point = rand() % GENE_LENGTH;for (int i = 0; i < crossover_point; i++) {offspring[0].genes[i] = parents[0].genes[i];offspring[1].genes[i] = parents[1].genes[i];}for (int i = crossover_point; i < GENE_LENGTH; i++) {offspring[0].genes[i] = parents[1].genes[i];offspring[1].genes[i] = parents[0].genes[i];}offspring[0].fitness = calculate_fitness(&offspring[0]);offspring[1].fitness = calculate_fitness(&offspring[1]);}void mutation(Individual* individual) {// 变异操作,以一定概率翻转基因位上的值for (int i = 0; i < GENE_LENGTH; i++) {if (rand() / (double)RAND_MAX < MUTATION_RATE) {individual->genes[i] = individual->genes[i] == '0' ? '1' : '0'; }}individual->fitness = calculate_fitness(individual);}void replace(Individual* population, Individual* offspring) {// 替换操作,将两个子代个体中适应度更高的一个替换掉种群中适应度最低的一个个体int worst_index = -1;double worst_fitness = INFINITY;for (int i = 0; i < POPULATION_SIZE; i++) {if (population[i].fitness < worst_fitness) {worst_index = i;worst_fitness = population[i].fitness;}}if (offspring[0].fitness > worst_fitness || offspring[1].fitness > worst_fitness) {if (offspring[0].fitness > offspring[1].fitness) {population[worst_index] = offspring[0];} else {population[worst_index] = offspring[1];}}}。
遗传算法( GA , Genetic Algorithm ) ,也称进化算法。
遗传算法是受达尔文的进化论的启发,借鉴生物进化过程而提出的一种启发式搜索算法。
因此在介绍遗传算法前有必要简单的介绍生物进化知识。
一.进化论知识作为遗传算法生物背景的介绍,下面内容了解即可:种群(Population):生物的进化以群体的形式进行,这样的一个群体称为种群。
个体:组成种群的单个生物。
基因 ( Gene ) :一个遗传因子。
染色体 ( Chromosome ):包含一组的基因。
生存竞争,适者生存:对环境适应度高的、牛B的个体参与繁殖的机会比较多,后代就会越来越多。
适应度低的个体参与繁殖的机会比较少,后代就会越来越少。
遗传与变异:新个体会遗传父母双方各一部分的基因,同时有一定的概率发生基因变异。
简单说来就是:繁殖过程,会发生基因交叉( Crossover ) ,基因突变( Mutation ) ,适应度( Fitness )低的个体会被逐步淘汰,而适应度高的个体会越来越多。
那么经过N代的自然选择后,保存下来的个体都是适应度很高的,其中很可能包含史上产生的适应度最高的那个个体。
二.遗传算法思想借鉴生物进化论,遗传算法将要解决的问题模拟成一个生物进化的过程,通过复制、交叉、突变等操作产生下一代的解,并逐步淘汰掉适应度函数值低的解,增加适应度函数值高的解。
这样进化N代后就很有可能会进化出适应度函数值很高的个体。
举个例子,使用遗传算法解决“0-1背包问题”的思路:0-1背包的解可以编码为一串0-1字符串(0:不取,1:取);首先,随机产生M个0-1字符串,然后评价这些0-1字符串作为0-1背包问题的解的优劣;然后,随机选择一些字符串通过交叉、突变等操作产生下一代的M个字符串,而且较优的解被选中的概率要比较高。
这样经过G代的进化后就可能会产生出0-1背包问题的一个“近似最优解”。
编码:需要将问题的解编码成字符串的形式才能使用遗传算法。
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。