gamultiobj
的自定义输出函数
此示例展示了如何为 gamultiobj
创建一个自定义输出函数,该函数每 20 代打印最佳目标函数值。向量目标函数有三个维度,是两个变量的函数。
function F = fitnessfcn(x) F = [norm(x)^2,... 0.5*norm(x(:)-[2;-1])^2+2,... 2*norm(x(:)-[-2;-1])^2-1]; end
要监控优化的进度,请创建一个具有 输出函数的结构 中描述的语法的输出函数。为了使输出保持合理长度,每 20 代打印三个目标函数找到的最佳(最小)值。
function [state,options,optchanged] = gamextent(options,state,flag) optchanged = false; switch flag case "init" disp("Best function values in each dimension for this generation") case "iter" if mod(state.Generation,20) == 1 % Suppress 95% of iterations. fprintf("Generation %-.0f\n",state.Generation) score = state.Score; nobj = size(score,2); [~,indx] = min(score); % Find indices of minimal objective function values. for i=1:nobj % Print scores for the smallest objective function values % in each dimension. fprintf("%-.3f ",score(indx(i),:)) fprintf("\n") end fprintf("\n") % Blank line before next output end end end
设置调用输出函数的选项,然后运行求解器。
opts = optimoptions("gamultiobj",OutputFcn=@gamextent); rng default % For reproducibility x = gamultiobj(@fitnessfcn,2,[],[],[],[],[],[],[],opts);
Best function values in each dimension for this generation Generation 1 2.568 9.068 10.845 4.085 2.078 30.132 3.478 7.478 0.240 Generation 21 0.001 4.446 9.073 5.135 2.001 31.589 4.983 9.955 -0.999 Generation 41 0.000 4.514 9.042 5.020 2.000 31.151 4.983 9.955 -0.999 Generation 61 0.000 4.508 9.061 5.020 2.000 31.151 4.943 9.964 -1.000 Generation 81 0.000 4.494 8.989 5.021 2.000 31.151 4.943 9.964 -1.000 Generation 101 0.000 4.497 9.003 5.017 2.000 31.026 5.003 9.989 -1.000 gamultiobj stopped because the average change in the spread of Pareto solutions is less than options.FunctionTolerance.
随着迭代的进行,第一个目标函数的最佳值接近 0,第二个目标函数的最佳值接近 2,第三个目标函数的最佳值接近 -1。您可以在每一代的主对角线上看到这种方法。