scipy.optimize.minimize 抛出错误:只有 size-1 数组可以转换为 Python 标量
我想最小化具有某些约束的函数。在下面的代码中,A= 4 x 4 矩阵,v= 4 x 1 向量,alpha 是随机标量值。为了避免错误“只有 size-1 数组可以转换为 Python 标量”,我对约束和目标函数进行了向量化。然而,仍然没有运气,并且出现了同样的错误。
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")
回溯错误消息是:-
------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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜没有没有正确的错误消息,但是这里有一些看起来可疑的代码。
查看
最小化
文档,并告诉我这是否是合法参数。Without a proper error message I'm guessing, but here's a bit of code that looks suspicious.
Review the
minimize
docs, and tell me if that is a legitimate parameter.