主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

从文件运行 ga

命令行界面使您能够使用文件多次运行遗传算法,并使用不同的选项设置。例如,您可以运行具有不同交叉分数设置的遗传算法,以查看哪一个能产生最佳结果。下面的代码运行函数 ga 21 次,将 options.CrossoverFraction 从 0 变化到 1,增量为 0.05,并记录结果。

options = optimoptions('ga','MaxGenerations',300,'Display','none');
rng default % for reproducibility
record=[];
for n=0:.05:1
  options = optimoptions(options,'CrossoverFraction',n);
  [x,fval]=ga(@rastriginsfcn,2,[],[],[],[],[],[],[],options);
  record = [record; fval];
end

绘制 fval 的值与交叉分数的关系图。

plot(0:.05:1, record);
xlabel('Crossover Fraction');
ylabel('fval')

Figure contains an axes object. The axes object with xlabel Crossover Fraction, ylabel fval contains an object of type line.

该图表明,将 options.CrossoverFraction 设置为 0.4 和 0.8 之间的某个值可以获得最佳结果。

通过运行 fval 20 次并计算每个交叉分数的 fval 值的平均值,您可以获得 ga 作为交叉分数函数的更平滑的图。

options = optimoptions('ga','MaxGenerations',300,'Display','none');
rng default % for reproducibility
record=[]; fval = zeros(20,1);
for n=0:.05:1
  options = optimoptions(options,'CrossoverFraction', n);
  for i = 1:20
      [x,fval(i)]=ga(@rastriginsfcn,2,[],[],[],[],[],[],[],options);
  end
  meanf = mean(fval);
  record = [record; meanf];
end

plot(0:.05:1, record);
xlabel('Crossover Fraction');
ylabel('fval')

Figure contains an axes object. The axes object with xlabel Crossover Fraction, ylabel fval contains an object of type line.

该图还表明 options.CrossoverFraction 的最佳选择范围是 0.4 到 0.8。

另请参阅

主题