美文网首页
优化算法matlab实现(二十八)蝗虫算法matlab实现

优化算法matlab实现(二十八)蝗虫算法matlab实现

作者: stronghorse | 来源:发表于2022-09-06 18:23 被阅读0次

    注意:此代码实现的是求目标函数最大值,求最小值可将适应度函数乘以-1(框架代码已实现)。
    注意:此代码实现的是求目标函数最大值,求最小值可将适应度函数乘以-1(框架代码已实现)。
    注意:此代码实现的是求目标函数最大值,求最小值可将适应度函数乘以-1(框架代码已实现)。

    1.代码实现

    不了解蝗虫算法可以先看看优化算法笔记(二十八)蝗虫算法
    实现代码前需要先完成优化算法matlab实现(二)框架编写中的框架的编写。

    文件名 描述
    ..\optimization algorithm\frame\Unit.m 个体
    ..\optimization algorithm\frame\Algorithm_Impl.m 算法主体

    以及优化算法matlab实现(四)测试粒子群算法中的测试函数、函数图像的编写。

    文件名 描述
    ..\optimization algorithm\frame\Get_Functions_details.m 测试函数,求值用
    ..\optimization algorithm\frame\func_plot.m 函数图像,画图用

    蝗虫算法的个体没有独有属性。
    蝗虫算法个体
    文件名:.. \optimization algorithm\algorithm_grasshopper\GOA_Unit.m

    % 蝗虫算法个体
    classdef GOA_Unit < Unit
        
        properties
        end
        
        methods
            function self = GOA_Unit()
            end
        end
     
    end
    

    蝗虫算法算法主体
    文件名:..\optimization algorithm\algorithm_grasshopper\GOA_Base.m

    % 蝗虫算法
    classdef GOA_Base  < Algorithm_Impl
        
        properties
            % 算法名称
            name = 'GOA';
    
        end
        
        % 外部可调用的方法
        methods
            function self = GOA_Base(dim,size,iter_max,range_min_list,range_max_list)
                % 调用父类构造函数
                self@Algorithm_Impl(dim,size,iter_max,range_min_list,range_max_list);
                self.name ='GOA';
            end
        end
        
        % 继承重写父类的方法
        methods (Access = protected)
            % 初始化种群
            function init(self)
                init@Algorithm_Impl(self)
                %初始化种群
                for i = 1:self.size
                    unit = GOA_Unit();
                    % 随机初始化位置:rand(0,1).*(max-min)+min
                    unit.position = unifrnd(self.range_min_list,self.range_max_list);
                    % 计算适应度值
                    unit.value = self.cal_fitfunction(unit.position);
                    % 将个体加入群体数组
                    self.unit_list = [self.unit_list,unit];
                end
            end
            
            % 每一代的更新
            function update(self,iter)
                update@Algorithm_Impl(self,iter)
                % 获取最优个体id
                best_id = self.get_best_id();
                % 获取该代的变量c
                c = self.get_c(iter);
    
                for i = 1:self.size
                    % 获取每一维的最大距离
                    dist_dim_max = self.get_dist_dim_max(i) + realmin('double');
    
                    new_pos = zeros(1,self.dim);
                    for j = 1:self.size
                        if  i == j
                            continue
                        end
                        % 获取两个体间距离,加上较小数,避免分母为0
                        distance = self.get_distance(i,j)+ realmin('double');
                        dist_dim = abs(self.unit_list(i).position-self.unit_list(j).position);
                        
                        % 将距离归一化到1-4
                        dis_dim_norm = self.norm(1,4,dist_dim,dist_dim_max);
                        dist_ij = (self.unit_list(i).position-self.unit_list(j).position);
                        new_pos = new_pos + self.get_s(dis_dim_norm).*dist_ij./distance;
                    end
                    
                    new_pos = c^2*(self.range_max_list-self.range_min_list)/2.*new_pos+self.unit_list(best_id).position;
                    
                    % 越界检查
                    new_pos = self.get_out_bound_value(new_pos);
                    new_value = self.cal_fitfunction(new_pos);
                    % 贪心一下
                    if new_value > self.unit_list(i).value
                        self.unit_list(i).value = new_value;
                        self.unit_list(i).position = new_pos;
                    end
                end
                
            end
            
            % 获取每一维上距其他个体的最大距离
            function dist_dim_max = get_dist_dim_max(self,i)
                dist_dim_max = zeros(1,self.dim);
                for j = 1:self.size
                    if i == j
                        continue
                    end
                    dist_dim = abs(self.unit_list(i).position-self.unit_list(j).position);
                    I = dist_dim>dist_dim_max;
                    dist_dim_max(I) = dist_dim(I);
                end
            end
            
            % 获取距离其他个体的距离(欧式)
            function distance = get_distance(self,i,j)
                distance = sqrt(sum((self.unit_list(i).position - self.unit_list(j).position).^2));
            end
            
            % 归一化,将值归一化到[min,max]区间内
            function result = norm(self,min,max,value,value_max)
                result = min + (max-min).*value./value_max;
            end
            
            % 变量c
            function c = get_c(self,iter)
                c_max = 1;
                c_min = 0.00001;
                c = c_max-iter*(c_max-c_min)/self.iter_max;
            end
            
            % 函数s
            function s = get_s(self,x)
                f = 0.5;
                l = 1.5;
                s = f*exp(-x/l) - exp(-x);
            end
            
            % 获取当前最优个体的id
            function best_id=get_best_id(self)
                % 求最大值则降序排列
                [value,index] = sort([self.unit_list.value],'descend');
                best_id = index(1);
            end
    
            
        end
    end
    

    文件名:..\optimization algorithm\algorithm_grasshopper\GOA_Impl.m
    算法实现,继承于Base,图方便也可不写,直接用GOA_Base,这里为了命名一致。

    % 蝗虫算法实现
    classdef GOA_Impl < GOA_Base
       
        % 外部可调用的方法
        methods
            function self = GOA_Impl(dim,size,iter_max,range_min_list,range_max_list)
                % 调用父类构造函数设置参数
                 self@GOA_Base(dim,size,iter_max,range_min_list,range_max_list);
            end
        end 
    end
    

    2.测试

    测试F1
    文件名:..\optimization algorithm\algorithm_grasshopper\Test.m

    %% 清理之前的数据
    % 清除所有数据
    clear all;
    % 清除窗口输出
    clc;
    
    %% 添加目录
    % 将上级目录中的frame文件夹加入路径
    addpath('../frame')
    
    
    %% 选择测试函数
    Function_name='F1';
    %[最小值,最大值,维度,测试函数]
    [lb,ub,dim,fobj]=Get_Functions_details(Function_name);
    
    %% 算法实例
    % 种群数量
    size = 50;
    % 最大迭代次数
    iter_max = 1000;
    % 取值范围上界
    range_max_list = ones(1,dim).*ub;
    % 取值范围下界
    range_min_list = ones(1,dim).*lb;
    
    % 实例化蝗虫算法类
    base = GOA_Impl(dim,size,iter_max,range_min_list,range_max_list);
    base.is_cal_max = false;
    % 确定适应度函数
    base.fitfunction = fobj;
    % 运行
    base.run();
    disp(base.cal_fit_num);
    
    %% 绘制图像
    figure('Position',[500 500 660 290])
    %Draw search space
    subplot(1,2,1);
    func_plot(Function_name);
    title('Parameter space')
    xlabel('x_1');
    ylabel('x_2');
    zlabel([Function_name,'( x_1 , x_2 )'])
    %Draw objective space
    subplot(1,2,2);
    % 绘制曲线,由于算法是求最大值,适应度函数为求最小值,故乘了-1,此时去掉-1
    semilogy((base.value_best_history),'Color','r')
    title('Objective space')
    xlabel('Iteration');
    ylabel('Best score obtained so far');
    % 将坐标轴调整为紧凑型
    axis tight
    % 添加网格
    grid on
    % 四边都显示刻度
    box off
    legend(base.name)
    display(['The best solution obtained by ',base.name ,' is ', num2str(base.value_best)]);
    display(['The best optimal value of the objective funciton found by ',base.name ,' is ', num2str(base.position_best)]);
    

    相关文章

      网友评论

          本文标题:优化算法matlab实现(二十八)蝗虫算法matlab实现

          本文链接:https://www.haomeiwen.com/subject/retwnrtx.html