scipy.optimize.minimize 抛出错误:只有 size-1 数组可以转换为 Python 标量

发布于 2025-01-17 15:51:38 字数 2331 浏览 2 评论 0原文

我想最小化具有某些约束的函数。在下面的代码中,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

昇り龍 2025-01-24 15:51:38

我猜没有没有正确的错误消息,但是这里有一些看起来可疑的代码。

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]])]

查看最小化文档,并告诉我这是否是合法参数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文