Problem
I guess scipy.optimize.minimize cannot use 2D bounds.
I can work around the problem by:
- reshape input to
minimizeto 1D arrays - reshape the arrays back to 2D within the objective function.
But that is tedious.
Did I do something wrong? Or minimize really cannot use 2D bounds?
The variables should be all between 0 and 1 in my case.
Thanks.
Doc
The doc for version 1.1.0 says bounds can be an array:
scipy.optimize.Bounds
...
Parameters:
lb, ub : array_like, optional
Lower and upper bounds on independent variables. Each array must have the same size as x or be a scalar, in which case a bound will be the same for all the variables. ...
Versions
- Python 3.6.2 |Anaconda custom (64-bit)
- numpy: 1.14.2 in anaconda
- scipy: 1.1.0 in anaconda
Test
import numpy as np
import scipy
import scipy.optimize as opt
def obj(x):
return x.sum()
def main():
x = np.ones((3, 4))
bounds = opt.Bounds(np.zeros(x.shape),
np.ones(x.shape))
r = opt.minimize(obj, x, bounds=bounds)
print(r)
main()
Result
Traceback (most recent call last):
File "scipy_bounds.py", line 16, in <module>
main()
File "scipy_bounds.py", line 12, in main
r = opt.minimize(obj, x, bounds=bounds)
File "<...>/site-packages/scipy/optimize/_minimize.py", line 584, in minimize
bounds = new_bounds_to_old(bounds.lb, bounds.ub, x0.shape[0])
File "<...>/site-packages/scipy/optimize/_constraints.py", line 259, in new_bounds_to_old
lb = [x if x > -np.inf else None for x in lb]
File "<...>/site-packages/scipy/optimize/_constraints.py", line 259, in <listcomp>
lb = [x if x > -np.inf else None for x in lb]
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I found that minimize doesn't let me use scalar bounds too.
I get 'length of x0 != length of bounds'.