3

我正在使用 NLOpt 的 Python 接口进行优化。在某个时刻,经过多次迭代,我得到一个 nlopt.RoundoffLimited 异常。根据文档(http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference#Error_codes_.28negative_return_values.29),在出现此类异常后,“优化通常仍会返回有用的结果”。我如何实际查看中间结果?我正在运行如下代码:

opt = nlopt.opt(...)
# ... some optimization settings
try:
    opt_results = opt.optimize(guess)
except nlopt.RoundoffLimited:
    # How do I get the latest parameters from opt,
    # after the optimization has failed?

我可以很好地使用 获得目标值opt.last_optimize_result(),但我找不到 API 调用来获取导致该目标值的参数。

谢谢!

4

1 回答 1

0

我仍然没有找到一个特别优雅的解决方案,但我现在会发布这个,以防有人偶然发现同样的问题。这是在优化异常之前恢复先前有效优化参数的一种方法:

# globals
previous_args = None
current_args = None

# objective function
def objective_function(args, gradient):
    global previous_args
    global current_args

    previous_args = current_args
    current_args = args

    # ... the rest of your objective function
    return function_value

# optimization code using objective_function
opt = nlopt.opt(...)

try:
    args = opt.optimize(guess)
except nlopt.RoundoffLimited:
    args = previous_args

    # you should do some sanity checks on args.
    # for example, one reason you may see RoundoffLimited
    # is args on the order of 1e-300 or so.
于 2014-03-31T01:06:00.523 回答