In order to get familiar with global optimization methods and in particular with the shgo
optimizer from scipy.optimize v1.3.0
I have tried to minimize the variance var(x)
of a vector x = [x1,...,xN]
with 0 <= xi <= 1
under the constraint that x
has a given average value:
import numpy as np
from scipy.optimize import shgo
# Constraint
avg = 0.5 # Given average value of x
cons = {'type': 'eq', 'fun': lambda x: np.mean(x)-avg}
# Minimize the variance of x under the given constraint
res = shgo(lambda x: np.var(x), bounds=6*[(0, 1)], constraints=cons)
The shgo
method fails on this problem:
>>> res
fun: 0.0
message: 'Failed to find a feasible minimiser point. Lowest sampling point = 0.0'
nfev: 65
nit: 2
nlfev: 0
nlhev: 0
nljev: 0
success: False
x: array([0., 0., 0., 0., 0., 0.])
The correct solution would be the uniform distribution x = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5]
and it can be easily found by using the local optimizer minimize
from scipy.optimize
:
from scipy.optimize import minimize
from numpy.random import random
x0 = random(6) # Random start vector
res2 = minimize(lambda x: np.var(x), x0, bounds=6*[(0, 1)], constraints=cons)
The minimize
method yields the correct result for arbitrary start vectors:
>>> res2.success
True
>>> res2.x
array([0.5, 0.5, 0.5, 0.5, 0.5, 0.5])
My question is: Why shgo
fails on this relatively simple task? Did I made a mistake or is shgo
simply not usable for this problem? Any help would be greatly appreciated.