使用检查点文件
用于重启的检查点
检查点文件包含有关优化过程的数据。要获取检查点文件,请使用 CheckpointFile
选项。
检查点文件的一个基本用途是在优化过早停止时恢复优化。提前停止的原因可能是电源故障或崩溃等事件,或者当您在绘图函数窗口中按下停止按钮时。
无论提前停止的原因是什么,重新启动过程只需使用检查点文件名调用 surrogateopt
。
例如,假设您使用 'check1'
检查点文件运行优化,然后在优化开始后立即点击停止按钮。
options = optimoptions('surrogateopt','CheckpointFile','check1.mat'); lb = [-6,-8]; ub = -lb; fun = @(x)100*(x(2) - x(1)^2)^2 + (1 - x(1))^2; [x,fval,exitflag,output] = surrogateopt(fun,lb,ub,options)
Optimization stopped by a plot function or output function. x = 0 0 fval = 1 exitflag = -1 output = struct with fields: elapsedtime: 6.7739 funccount: 18 constrviolation: 0 ineq: [1×0 double] rngstate: [1×1 struct] message: 'Optimization stopped by a plot function or output function.'
要恢复优化,请使用 'check1.mat'
参量调用 surrogateopt
。
[x,fval,exitflag,output] = surrogateopt('check1.mat')
surrogateopt stopped because it exceeded the function evaluation limit set by 'options.MaxFunctionEvaluations'. x = 0.8299 0.6861 fval = 0.0296 exitflag = 0 output = struct with fields: elapsedtime: 78.7419 funccount: 200 constrviolation: 0 ineq: [1×0 double] rngstate: [1×1 struct] message: 'surrogateopt stopped because it exceeded the function evaluation limit set by ↵'options.MaxFunctionEvaluations'.'
更改选项以扩展或监控优化
您可以通过更改选项中的停止条件来扩展优化,无论优化是否由于不可预见的事件而停止。您还可以通过显示每次迭代的信息来监控优化情况。
注意
surrogateopt
仅允许您更改有限的一组选项。为了可靠性,请更新原始选项结构体,而不是创建新选项。
有关重新启动时可以更改的选项列表,请参阅 opts
。
例如,假设您想要扩展之前的优化以运行总共 400 次函数计算。此外,您还想使用 'surrogateoptplot'
绘图函数来监控优化。
opts = optimoptions(options,'MaxFunctionEvaluations',400,... 'PlotFcn','surrogateoptplot'); [x,fval,exitflag,output] = surrogateopt('check1.mat',opts)
surrogateopt stopped because it exceeded the function evaluation limit set by 'options.MaxFunctionEvaluations'. x = 1.0369 1.0758 fval = 0.0014 exitflag = 0 output = struct with fields: elapsedtime: 177.8927 funccount: 400 constrviolation: 0 ineq: [1×0 double] rngstate: [1×1 struct] message: 'surrogateopt stopped because it exceeded the function evaluation limit set by ↵'options.MaxFunctionEvaluations'.'
新的绘图函数从优化开始就开始绘图,即使您是在求解器停止在函数评估编号 200 之后才启动绘图函数。'surrogateoptplot'
绘图函数还显示优化停止的位置以及从检查点文件重新启动的位置的评估数字。
稳健替代优化代码
要仅当文件存在时从检查点文件重新启动替代优化,请使用以下代码逻辑。通过这种方式,您可以编写脚本来保持优化,即使在发生崩溃或其他意外事件之后也是如此。
% Assume that myfun, lb, and ub exist if isfile('saveddata.mat') [x,fval,exitflag,output] = surrogateopt('saveddata.mat'); else options = optimoptions("surrogateopt","CheckpointFile",'saveddata.mat'); [x,fval,exitflag,output] = surrogateopt(myfun,lb,ub,options); end