这里用到的源码是从https://cn.mathworks.com/matlabcentral/fileexchange/10429-nsga-ii--a-multi-objective-optimization-algorithm 下载的,网上搜到说这个比较好,看了看挺简洁的,注释也很全面,自己一边看一边把注释都翻译成中文的,分享出来给初学者们一起学习下哈哈。
1.主程序
function nsga_2(pop,gen)
%% function nsga_2(pop,gen)
% is a multi-objective optimization function where the input arguments are
% pop - Population size
% gen - Total number of generations
% 这是一个多目标优化函数,pop是种群大小,gen是进化代数。
% This functions is based on evolutionary algorithm for finding the optimal
% solution for multiple objective i.e. pareto front for the objectives.
% Initially enter only the population size and the stoping criteria or
% the total number of generations after which the algorithm will
% automatically stopped.
%该函数基于多目标进化算法求解最优方案,即多目标的帕累托前沿。
%最初只输入种群规模和终止条件。
% You will be asked to enter the number of objective functions, the number
% of decision variables and the range space for the decision variables.
%你需要输入目标个数和决策变量个数,以及决策变量的空间范围。
% Also you will have to define your own objective funciton by editing the
% evaluate_objective() function. A sample objective function is described
% in evaluate_objective.m. Kindly make sure that the objective function
% which you define match the number of objectives that you have entered as
% well as the number of decision variables that you have entered. The
% decision variable space is continuous for this function, but the
% objective space may or may not be continuous.
%你还需要通过编辑evaluate_objective()函数来定义你自己的目标函数;evaluate_objective.m里定义了一个目标函数的例子。
%请确保你定义的目标函数与你输入的目标个数、决策变量个数相匹配。该函数的决策变量空间是连续的,但是目标空间可以是连续或者离散的。
%另外网上资料说objective_description_function.m 要自己重写
% Original algorithm NSGA-II was developed by researchers in Kanpur Genetic
% Algorithm Labarotary and kindly visit their website for more information
% http://www.iitk.ac.in/kangal/
% Copyright (c) 2009, Aravind Seshadri
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
%% Simple error checking 错误处理
% Number of Arguments
% Check for the number of arguments. The two input arguments are necessary
% to run this function.
%确认必要的两个输入已经定义
if nargin < 2
%error('NSGA-II: Please enter the population size and number of generations as input arguments.');
error('NSGA-II:请输入种群大小和迭代次数!');
end
% Both the input arguments need to of integer data type
%两个输入都需要是整数
if isnumeric(pop) == 0 || isnumeric(gen) == 0
%error('Both input arguments pop and gen should be integer datatype');
error('NSGA-II:两个输入参数必须是整数!');
end
% Minimum population size has to be 20 individuals
%种群大小至少为20
if pop < 20
%error('Minimum population for running this function is 20');
error('种群大小至少为20');
end
if gen < 5
%error('Minimum number of generations is 5');
error('迭代次数至少为5');
end
% Make sure pop and gen are integers
%再次确保pop和gen是整数
pop = round(pop);
gen = round(gen);
%% Objective Function 目标函数
% The objective function description contains information about the
% objective function. M is the dimension of the objective space, V is the
% dimension of decision variable space, min_range and max_range are the
% range for the variables in the decision variable space. User has to
% define the objective functions using the decision variables. Make sure to
% edit the function 'evaluate_objective' to suit your needs.
%目标函数,描述为四元组。M是目标空间维度,V是决策空间维度,min_range 和 max_range
%是决策变量的取值范围。使用者需要使用决策变量来定义目标函数。确保将evaluate_objective
%函数修改为适合你的需求的目标函数
%
[M, V, min_range, max_range] = objective_description_function();
%% Initialize the population 初始化种群
% Population is initialized with random values which are within the
% specified range. Each chromosome consists of the decision variables. Also
% the value of the objective functions, rank and crowding distance
% information is also added to the chromosome vector but only the elements
% of the vector which has the decision variables are operated upon to
% perform the genetic operations like corssover and mutation.
%在指定的决策变量取值范围内生成随机值来初始化种群。每个染色体由决策变量组成。
%同样的,目标函数值,排序和拥挤距离信息也添加到染色体向量中。
%但只对具有决策变量的染色体片段进行进行遗传操作,如交叉和变异。
%
chromosome = initialize_variables(pop, M, V, min_range, max_range);
%% Sort the initialized population 对初始种群进行排序
% Sort the population using non-domination-sort. This returns two columns
% for each individual which are the rank and the crowding distance
% corresponding to their position in the front they belong. At this stage
% the rank and the crowding distance for each chromosome is added to the
% chromosome vector for easy of computation.
% 使用非支配排序对种群进行排序。该函数返回每个个体对应的排序值和拥挤距离,是一个两列的矩阵。
% 并将排序值和拥挤距离添加到染色体矩阵中
chromosome = non_domination_sort_mod(chromosome, M, V);
%% Start the evolution process 开始进化过程
% The following are performed in each generation
% * Select the parents which are fit for reproduction
% * Perfrom crossover and Mutation operator on the selected parents
% * Perform Selection from the parents and the offsprings
% * Replace the unfit individuals with the fit individuals to maintain a
% constant population size.
%对每一代种群进行如下操作:
%1.选择适合繁殖的父代
%2.对选中的父代进行交叉变异
%3.对父代及其子代进行选择
%4.用适应性好的个体替换不好的个体以保持恒定的人口规模
for i = 1 : gen
% Select the parents 选择父代
% Parents are selected for reproduction to generate offspring. The
% original NSGA-II uses a binary tournament selection based on the
% crowded-comparision operator. The arguments are
%基于拥挤距离比较,使用二元锦标赛选择父代,其中的参数有:
% pool - size of the mating pool. It is common to have this to be half the
% population size.
%交配池大小,通常设置为种群大小的一半
% tour - Tournament size. Original NSGA-II uses a binary tournament
% selection, but to see the effect of tournament size this is kept
% arbitary, to be choosen by the user.
%竞标赛参赛者数目,NSGA-II原本设为2,但这里设为可调参数
pool = round(pop/2);
tour = 2;
% Selection process 选择操作
% A binary tournament selection is employed in NSGA-II. In a binary
% tournament selection process two individuals are selected at random
% and their fitness is compared. The individual with better fitness is
% selcted as a parent. Tournament selection is carried out until the
% pool size is filled. Basically a pool size is the number of parents
% to be selected. The input arguments to the function
% tournament_selection are chromosome, pool, tour. The function uses
% only the information from last two elements in the chromosome vector.
% The last element has the crowding distance information while the
% penultimate element has the rank information. Selection is based on
% rank and if individuals with same rank are encountered, crowding
% distance is compared. A lower rank and higher crowding distance is
% the selection criteria.
%巴拉巴拉一堆锦标赛解释不翻译了。tournament_selection 函数的输入变量为chromosome, pool, tour
%chromosome中只有最后的个元素被使用了(排序值和拥挤距离),选择标准不解释
parent_chromosome = tournament_selection(chromosome, pool, tour);
% Perfrom crossover and Mutation operator 进行交叉和变异
% The original NSGA-II algorithm uses Simulated Binary Crossover (SBX) and
% Polynomial mutation. Crossover probability pc = 0.9 and mutation
% probability is pm = 1/n, where n is the number of decision variables.
% Both real-coded GA and binary-coded GA are implemented in the original
% algorithm, while in this program only the real-coded GA is considered.
% The distribution indeices for crossover and mutation operators as mu = 20
% and mum = 20 respectively.
% 原始的NSGA-II使用SBX和 Polynomial mutation。交叉概率pc=0.9,变异概率是1/n(n是决策变量个数)
% 并且实现了实数编码遗传算法和二进制编码遗传算法。本程序中只考虑实数编码。
% 交叉和变异的 分布指标 分别为mu = 20,mum = 20。
mu = 20;
mum = 20;
offspring_chromosome = genetic_operator(parent_chromosome,M, V, mu, mum, min_range, max_range);
% Intermediate population 中间(混合)种群
% Intermediate population is the combined population of parents and
% offsprings of the current generation. The population size is two
% times the initial population.
%混合种群是当前父代和子代的混合,种群大小是初始种群的两倍。
[main_pop,temp] = size(chromosome);
[offspring_pop,temp] = size(offspring_chromosome);
% temp is a dummy variable.
%temp是一个虚拟变量
clear temp
% intermediate_chromosome is a concatenation of current population and
% the offspring population.
intermediate_chromosome(1:main_pop,:) = chromosome;
intermediate_chromosome(main_pop + 1 : main_pop + offspring_pop,1 : M+V) = ...
offspring_chromosome;
% Non-domination-sort of intermediate population 对混合种群进行非支配排序
% The intermediate population is sorted again based on non-domination sort
% before the replacement operator is performed on the intermediate
% population. 在对混合种群进行替换之前需要进行非支配排序
intermediate_chromosome = ...
non_domination_sort_mod(intermediate_chromosome, M, V);
% Perform Selection 进行选择操作
% Once the intermediate population is sorted only the best solution is
% selected based on it rank and crowding distance. Each front is filled in
% ascending order until the addition of population size is reached. The
% last front is included in the population based on the individuals with
% least crowding distance
%在混合种群排序时,仅根据排序和拥挤距离选择最优解。
%每一个梯队都是按升序排列的,直到达到了人口规模上限。
%最后一个梯队基于拥挤距离最小来选择。
chromosome = replace_chromosome(intermediate_chromosome, M, V, pop);
if ~mod(i,100)
clc
%fprintf('%d generations completed\n',i);
fprintf('第%d 代迭代完成\n',i);
end
end
%% Result 结果
% Save the result in ASCII text format.
%将结果输出为ASCII text格式
save solution.txt chromosome -ASCII
%% Visualize 可视化输出
% The following is used to visualize the result if objective space
% dimension is visualizable.
if M == 2
plot(chromosome(:,V + 1),chromosome(:,V + 2),'*');
elseif M ==3
plot3(chromosome(:,V + 1),chromosome(:,V + 2),chromosome(:,V + 3),'*');
end
2.目标函数定义(默认2目标6变量)
function [number_of_objectives, number_of_decision_variables, min_range_of_decesion_variable, max_range_of_decesion_variable] = objective_description_function()
%% function [number_of_objectives, number_of_decision_variables, min_range_of_decesion_variable, max_range_of_decesion_variable] = objective_description_function()
% This function is used to completely describe the objective functions and
% the range for the decision variable space etc. The user is prompted for
% inputing the number of objectives, numebr of decision variables, the
% maximum and minimum range for each decision variable and finally the
% function waits for the user to modify the evaluate_objective function to
% suit their need.
%该函数用于对目标函数和决策变量进行完全的描述,用户会被要求输入目标和决策变量的个数
%以及决策变量范围。并且还需要用户调整 evaluate_objective 函数来适应其需求。
% Copyright (c) 2009, Aravind Seshadri
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
%g = sprintf('Input the number of objective: ');
g = sprintf('输入目标个数: ');
% Obtain the number of objective function 获取决策变量个数(Q/C/T 3个)
number_of_objectives = input(g);
if number_of_objectives < 2
%error('This is a multi-objective optimization function hence the minimum number of objectives is two');
error('至少两个目标,不然你要我干嘛');
end
%g = sprintf('\nInput the number of decision variables: ');
g = sprintf('\n输入决策变量个数: ');
% Obtain the number of decision variables 获取决策变量个数(这里与调度问题很不兼容)
number_of_decision_variables = input(g);
clc
for i = 1 : number_of_decision_variables
clc
%g = sprintf('\nInput the minimum value for decision variable %d : ', i);
g = sprintf('\n输入决策变量 %d 的最小值: ', i);
% Obtain the minimum possible value for each decision variable
min_range_of_decesion_variable(i) = input(g);
%g = sprintf('\nInput the maximum value for decision variable %d : ', i);
g = sprintf('\n输入决策变量 %d 的最大值: ', i);
% Obtain the maximum possible value for each decision variable
max_range_of_decesion_variable(i) = input(g);
clc
end
g = sprintf('\n Now edit the function named "evaluate_objective" appropriately to match your needs.\n Make sure that the number of objective functions and decision variables match your numerical input. \n Make each objective function as a corresponding array element. \n After editing do not forget to save. \n Press "c" and enter to continue... ');
g = sprintf('\n 现在请编辑函数 "evaluate_objective" 从而与你的需求匹配.\n 确保决策变量和目标函数的数量与你现在输入的值相符. \n 将每个目标函数表示为相应的矩阵. \n 修改后注意保存. \n 输入 "c" 后回车继续... ');
% Prompt the user to edit the evaluate_objective function and wait until
% 'c' is pressed. 要求用户编辑evaluate_objective函数直到输入“c”
x = input(g, 's');
if isempty(x)
x = 'x';
end
while x ~= 'c'
clc
x = input(g, 's');
if isempty(x)
x = 'x';
end
end
3.初始化种群
function f = initialize_variables(N, M, V, min_range, max_range)
%% function f = initialize_variables(N, M, V, min_tange, max_range)
% This function initializes the chromosomes. Each chromosome has the
% following at this stage 该函数对染色体进行初始化,这一步中每个染色体包含以下两部分
% * set of decision variables 决策变量集合
% * objective function values 目标函数值
%
% where,
% N - Population size 种群大小
% M - Number of objective functions 目标函数个数
% V - Number of decision variables 决策变量个数
% min_range - A vector of decimal values which indicate the minimum value
% for each decision variable.
% max_range - Vector of maximum possible values for decision variables.
% Copyright (c) 2009, Aravind Seshadri
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
min = min_range;
max = max_range;
% K is the total number of array elements. For ease of computation decision
% variables and objective functions are concatenated to form a single
% array. For crossover and mutation only the decision variables are used
% while for selection, only the objective variable are utilized.
% K是数组的总元素个数。为了便于计算,决策变量和目标函数串在一起形成一个数组。
%对于交叉和变异,利用目标变量对决策变量进行选择。
K = M + V;
%% Initialize each chromosome 初始化每个染色体
% For each chromosome perform the following (N is the population size)
%对每个染色体进行以下操作(N是种群大小)
for i = 1 : N
% Initialize the decision variables based on the minimum and maximum
% possible values. V is the number of decision variable. A random
% number is picked between the minimum and maximum possible values for
% the each decision variable.
%基于决策变量范围对其进行初始化。
% V是决策变量个数,对每个决策变量,产生一个对应范围内的随机数
for j = 1 : V
f(i,j) = min(j) + (max(j) - min(j))*rand(1);
end
% For ease of computation and handling data the chromosome also has the
% vlaue of the objective function concatenated at the end. The elements
% V + 1 to K has the objective function valued.
%为了简化计算将对应的目标函数值储存在染色体的V + 1 到 K的位置。
% The function evaluate_objective takes one chromosome at a time,
% infact only the decision variables are passed to the function along
% with information about the number of objective functions which are
% processed and returns the value for the objective functions. These
% values are now stored at the end of the chromosome itself.
% 函数evaluate_objective每次对一个染色体进行操作,事实上它只对决策变量进行处理,
%并返回每个目标函数的值。从而目标函数值储存在了染色体末端。
f(i,V + 1: K) = evaluate_objective(f(i,:), M, V);
end
将遗传算法以及NSGA-II的原理了解之后,看完这几个函数就能知道整个程序的原理了,可以根据自己的问题进行数学建模。
由于我要做的是资源调度问题,建模会很复杂,所以最好的方式还是先做好一个基础的资源调度GA算法,再修改目标函数来应用NSGA-II。所以其他的几个函数还没有翻译,要是翻译了,会上传源码给大家下载——其实用原始的代码看英文注释就够啦哈哈。
最初的NSGA-II是用c语言的,最新版只能在Linux上运行,http://www.iitk.ac.in/kangal/codes.shtml 可以下载,以后要是研究了这个代码,会继续分享出来。