Stop Scipy minimize after set time

前端 未结 2 842
再見小時候
再見小時候 2020-12-03 15:46

I use minimize from the Scipy module on Python 3.4, specifically:

resultats=minimize(margin_rate, iniprices, method=\'SLSQP\',
jac=margin_rate_deriv, bounds=         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 16:11

    You can use the callback argument to raise a warning or exception if the execution time exceeds some threshold:

    import numpy as np
    from scipy.optimize import minimize, rosen
    import time
    import warnings
    
    class TookTooLong(Warning):
        pass
    
    class MinimizeStopper(object):
        def __init__(self, max_sec=60):
            self.max_sec = max_sec
            self.start = time.time()
        def __call__(self, xk=None):
            elapsed = time.time() - self.start
            if elapsed > self.max_sec:
                warnings.warn("Terminating optimization: time limit reached",
                              TookTooLong)
            else:
                # you might want to report other stuff here
                print("Elapsed: %.3f sec" % elapsed)
    
    # example usage
    x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
    res = minimize(rosen, x0, method='Nelder-Mead', callback=MinimizeStopper(1E-3))
    

提交回复
热议问题