【问题标题】:Getting NLOpt results after optimization failure using Python API使用 Python API 优化失败后获取 NLOpt 结果
【发布时间】:2023-03-05 21:28:01
【问题描述】:

我正在使用 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 调用来获取导致该目标值的参数。

谢谢!

【问题讨论】:

    标签: python-2.7 nlopt


    【解决方案1】:

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

    # 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.
    

    【讨论】:

    • 另一种方法是监视所有 f / 所有 x 值,并在您的函数周围使用包装器,例如 (ahem) funcmon.py
    • 哈,谢谢 =) 我想使用一些记忆装饰器也可以。可能比使用全局变量更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    相关资源
    最近更新 更多