简体   繁体   中英

How to access `success` attribute of OptimizeResult instance returned from scipy.optimize.basinhopping (NOT minimize)?

The Problem

According to the SciPy docs , the function scipy.optimize.basinhopping(...) returns an instance of OptimizeResult , which is basically a wrapper around a dictionary. I can print this instance and see success: True , but I would like to access it programmatically. In the case of a local minimization via scipy.optimize.minimize(...) - which, according to the SciPy docs , also returns an instance of OptimizeResult - the success value can be accessed as OptimizeResult.success . But, this does not work for the basinhopping routine. I find this odd because the SciPy docs for OptimizeResult show that success should be an allowed key.

My Question

How can I programmatically access the success value of OptimizeResult ?

Example Code

To recreate this issue (and to show it works in the case of minimize(...) ), see code below:

import numpy as np
from scipy.optimize import minimize, basinhopping, OptimizeResult

def pdf(prms, x):
    """ normal distribution pdf """
    return np.exp(- np.square((x - prms[0])/prms[1]) / 2) / (prms[1] * np.sqrt(2 * np.pi))

def nll(prms, x):
    """ negative log-likelihood """
    return np.log(pdf(prms, x))

def err_func(prms, x):
    """ maximum likelihood estimation """
    return -1 * np.sum(nll(prms, x))

prms = (50, 10) # true parameters: mean=50, std=10
data = np.random.normal(loc=prms[0], scale=prms[1], size=1000) # normal distribution
x0 = (30, 15) # initial parameter guess

local_result = minimize(err_func, x0, args=(data,), method='Nelder-Mead')
print("\n LOCAL EXTREMUM RESULT:\n{}\n".format(local_result))
print("\n .. LOCAL SUCCESS:\n{}\n".format(local_result.success))

minimizer_kwargs = {'args' : (data,), 'method' : 'Nelder-Mead'}
global_result = basinhopping(err_func, x0, minimizer_kwargs=minimizer_kwargs)
print("\n GLOBAL EXTREMUM RESULT:\n{}\n".format(global_result))
try:
    print("\n .. GLOBAL SUCCESS:\n{}\n".format(global_result.success))
except:
    suc = OptimizeResult(global_result)
    print("\n .. GLOBAL SUCCESS:\n{}\n".format(suc.success)) 

Example Output

The print statements above output the following:

 LOCAL EXTREMUM RESULT:
 final_simplex: (array([[49.81697641, 10.07216849],
       [49.81705723, 10.07218614],
       [49.81706317, 10.07208372]]), array([3728.71186314, 3728.71186315, 3728.71186316]))
           fun: 3728.711863138763
       message: 'Optimization terminated successfully.'
          nfev: 86
           nit: 44
        status: 0
       success: True
             x: array([49.81697641, 10.07216849])


 .. LOCAL SUCCESS:
True


 GLOBAL EXTREMUM RESULT:
                        fun: 3728.711863121894
 lowest_optimization_result:  final_simplex: (array([[49.81701209, 10.07213731],
       [49.81709255, 10.07216525],
       [49.81703196, 10.07220361]]), array([3728.71186312, 3728.71186315, 3728.71186316]))
           fun: 3728.711863121894
       message: 'Optimization terminated successfully.'
          nfev: 63
           nit: 31
        status: 0
       success: True
             x: array([49.81701209, 10.07213731])
                    message: ['requested number of basinhopping iterations completed successfully']
      minimization_failures: 0
                       nfev: 6455
                        nit: 100
                          x: array([49.81701209, 10.07213731])

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/scipy/optimize/optimize.py", line 114, in __getattr__
    return self[name]
KeyError: 'success'



During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "stacko.py", line 28, in <module>
    print("\n .. GLOBAL SUCCESS:\n{}\n".format(global_result.success))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/scipy/optimize/optimize.py", line 116, in __getattr__
    raise AttributeError(name)
AttributeError: success

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/scipy/optimize/optimize.py", line 114, in __getattr__
    return self[name]
KeyError: 'success'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "stacko.py", line 31, in <module>
    print("\n .. GLOBAL SUCCESS:\n{}\n".format(suc.success))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/scipy/optimize/optimize.py", line 116, in __getattr__
    raise AttributeError(name)
AttributeError: success

global_result结果具有属性lowest_optimization_result ,它本身就是OptimizeResult实例,所以你应该调用它的success

global_result.lowest_optimization_result.success

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM