Main Content

플롯 함수

실행 중 최적화 플로팅하기

솔버를 실행하는 동안 다양한 진행률 측정값을 플로팅할 수 있습니다. optimoptionsPlotFcn 이름-값 인수를 사용하여 매 반복 시 호출할 솔버에 대해 하나 이상의 플로팅 함수를 지정합니다. 함수 핸들, 함수 이름 또는 함수 핸들이나 함수 이름으로 구성된 셀형 배열을 PlotFcn 값으로 전달합니다.

각 솔버에는 미리 정의된 다양한 플롯 함수가 있습니다. 자세한 내용은 솔버에 대한 함수 도움말 페이지에서 PlotFcn 옵션 설명을 참조하십시오.

또한 사용자 지정 플롯 함수 만들기 항목에 나와 있듯이 사용자 지정 플롯 함수를 사용할 수도 있습니다. 동일한 구조체를 출력 함수로 사용하여 함수 파일을 작성합니다. 이 구조체에 대한 자세한 내용은 Output Function and Plot Function Syntax 항목을 참조하십시오.

미리 정의된 플롯 함수 사용하기

이 예제에서는 플롯 함수를 사용하여 fmincon "interior-point" 알고리즘의 진행률을 표시하는 방법을 보여줍니다. 이 문제는 최적화 라이브 편집기 작업 또는 솔버를 사용한, 제약 조건이 있는 비선형 문제에서 가져왔습니다.

비선형 목적 함수와 제약 조건 함수를 해당 기울기와 함께 작성합니다. 목적 함수는 로젠브록 함수입니다.

type rosenbrockwithgrad
function [f,g] = rosenbrockwithgrad(x)
% Calculate objective f
f = 100*(x(2) - x(1)^2)^2 + (1-x(1))^2;

if nargout > 1 % gradient required
    g = [-400*(x(2)-x(1)^2)*x(1)-2*(1-x(1));
        200*(x(2)-x(1)^2)];
end

이 파일을 rosenbrockwithgrad.m으로 저장합니다.

제약 조건 함수는 해가 norm(x)^2 <= 1을 충족하는 것입니다.

type unitdisk2
function [c,ceq,gc,gceq] = unitdisk2(x)
c = x(1)^2 + x(2)^2 - 1;
ceq = [ ];

if nargout > 2
    gc = [2*x(1);2*x(2)];
    gceq = [];
end

이 파일을 unitdisk2.m으로 저장합니다.

세 개의 플롯 함수 호출을 포함하는 솔버의 옵션을 만듭니다.

options = optimoptions(@fmincon,Algorithm="interior-point",...
 SpecifyObjectiveGradient=true,SpecifyConstraintGradient=true,...
 PlotFcn={@optimplotx,@optimplotfval,@optimplotfirstorderopt});

초기점 x0 = [0,0]을 만들고 나머지 입력값을 빈 값([])으로 설정합니다.

x0 = [0,0];
A = [];
b = [];
Aeq = [];
beq = [];
lb = [];
ub = [];

options를 포함하여 fmincon을 호출합니다.

fun = @rosenbrockwithgrad;
nonlcon = @unitdisk2;
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options)

Figure Optimization Plot Function contains 3 axes objects. Axes object 1 with title Current Point, xlabel Variable number, ylabel Current point contains an object of type bar. Axes object 2 with title Current Function Value: 0.0456748, xlabel Iteration, ylabel Function value contains an object of type scatter. Axes object 3 with title First-order Optimality: 2.16246e-08, xlabel Iteration, ylabel First-order optimality contains an object of type scatter.

Local minimum found that satisfies the constraints.

Optimization completed because the objective function is non-decreasing in 
feasible directions, to within the value of the optimality tolerance,
and constraints are satisfied to within the value of the constraint tolerance.
x = 1×2

    0.7864    0.6177

사용자 지정 플롯 함수 만들기

Optimization Toolbox™ 솔버에 대한 사용자 지정 플롯 함수를 만들려면 다음 구문을 사용하여 함수를 작성합니다.

function stop = plotfun(x,optimValues,state)
stop = false;
switch state
    case "init"
        % Set up plot
    case "iter"
        % Plot points
    case "done"
        % Clean up plots
    % Some solvers also use case "interrupt"
end
end

Global Optimization Toolbox 솔버는 다른 구문을 사용합니다.

x 데이터, optimValues 데이터, state 데이터가 사용자 플롯 함수에 전달됩니다. 전체 구문 세부 정보와 optimValues 인수의 데이터 목록은 Output Function and Plot Function Syntax 항목을 참조하십시오. PlotFcn 이름-값 인수를 사용하여 플롯 함수 이름을 솔버에 전달합니다.

예를 들어 이 예제의 마지막 부분에 나열되어 있는 plotfandgrad 헬퍼 함수는 목적 함수 값뿐만 아니라 스칼라 값을 가지는 목적 함수에 대한 기울기의 노름도 플로팅합니다. 이 예제의 마지막 부분에에 나열되어 있는 ras 헬퍼 함수를 목적 함수로 사용합니다. ras 함수에는 기울기 계산이 포함되어 있습니다. 따라서 효율성을 위해, SpecifyObjectiveGradient 이름-값 인수를 true로 설정합니다.

fun = @ras;
rng(1) % For reproducibility
x0 = 10*randn(2,1); % Random initial point
opts = optimoptions(@fminunc,SpecifyObjectiveGradient=true,PlotFcn=@plotfandgrad);
[x,fval] = fminunc(fun,x0,opts)

Figure Optimization Plot Function contains an axes object. The axes object contains 2 objects of type line. One or more of the lines displays its values using only markers These objects represent Objective, Norm(gradient).

Local minimum found.

Optimization completed because the size of the gradient is less than
the value of the optimality tolerance.
x = 2×1

    1.9949
    1.9949

fval = 17.9798

이 플롯은 제약 조건이 없는 최적화에 대해, 예상한 대로 기울기의 노름이 0으로 수렴되고 있음을 보여줍니다.

헬퍼 함수

다음 코드는 plotfandgrad 헬퍼 함수를 생성합니다.

function stop = plotfandgrad(x,optimValues,state)
persistent iters fvals grads % Retain these values throughout the optimization
stop = false;

switch state
    case "init"
        iters = [];
        fvals = [];
        grads = [];
    case "iter"
        iters = [iters optimValues.iteration];
        fvals = [fvals optimValues.fval];
        grads = [grads norm(optimValues.gradient)];
        plot(iters,fvals,"o",iters,grads,"x");
        legend("Objective","Norm(gradient)")
    case "done"
end
end

다음 코드는 ras 헬퍼 함수를 생성합니다.

function [f,g] = ras(x)
f = 20 + x(1)^2 + x(2)^2 - 10*cos(2*pi*x(1) + 2*pi*x(2));
if nargout > 1
    g(2) = 2*x(2) + 20*pi*sin(2*pi*x(1) + 2*pi*x(2));
    g(1) = 2*x(1) + 20*pi*sin(2*pi*x(1) + 2*pi*x(2));
end
end

관련 항목