'scipy.optimize.minimize throwing error: only size-1 arrays can be converted to Python scalars
I want to minimize a function with certain constrainsts. In the below code A= 4 by 4 matrix, v= 4 by 1 vector and alpha is a random scalar value. In order to avoid the error " only size-1 arrays can be converted to Python scalars", I have done vectorization of the constraint and the objective function. However, still no luck and the same error is appearing.
import random
from scipy.optimize import minimize
from numpy.linalg import norm
def calculateV(params):
return norm(params)
#Declaring the equation here
def objective(x):
alpha = x[0]
v=x[1:len(x)]
vnorm=calculateV(v)
return alpha+(vnorm/2)
#Need to vectorize the objective function to avoid only size 1 arrays can be converted
#to Python scalars
f=np.vectorize(objective)
#Declaring the constraint here
def constraint(x):
alpha=x[0]
v=x[1:len(x)]
vnorm=calculateV(v)
return A*v-alpha
c=np.vectorize(constraint)
#starting values
startalpha=random.random();
shape=(4,1)
startv=np.random.uniform(0,1,shape)
val_start=[startalpha,startv]
cons={'type':'ineq','fun':c}
result=minimize(f,val_start,constraints=cons,options={"disp":True})
if result.success:
print("Success")
else:
print("Sorry could not compute a minimum")
The traceback error message is :-
------Start--------
TypeError: only size-1 arrays can be converted to Python scalars
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<ipython-input-4-a3839c47e06a>", line 46, in <module>
result=minimize(objective,val_start,constraints=cons,options={"disp":True})
File "/usr/local/lib/python3.7/dist-packages/scipy/optimize/_minimize.py", line 618, in minimize
constraints, callback=callback, **options)
File "/usr/local/lib/python3.7/dist-packages/scipy/optimize/slsqp.py", line 308, in _minimize_slsqp
x = asfarray(x0).flatten()
File "<__array_function__ internals>", line 6, in asfarray
File "/usr/local/lib/python3.7/dist-packages/numpy/lib/type_check.py", line 114, in asfarray
return asarray(a, dtype=dtype)
ValueError: setting an array element with a sequence.
------End--------
/usr/local/lib/python3.7/dist-packages/scipy/optimize/_minimize.py:479: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
x0 = np.asarray(x0)
Solution 1:[1]
Without a proper error message I'm guessing, but here's a bit of code that looks suspicious.
In [236]: startalpha=random.random();
...: shape=(4,1)
...: startv=np.random.uniform(0,1,shape)
...: val_start=[startalpha,startv]
...:
In [237]: val_start
Out[237]:
[0.272350113689266,
array([[0.12736234],
[0.69036025],
[0.24118139],
[0.68033726]])]
Review the minimize docs, and tell me if that is a legitimate parameter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hpaulj |
