首页 新闻 搜索 专区 学院

ValueError: Objective function must return a scalar

0
悬赏园豆:5 [待解决问题]

我在使用python做马科维茨组合过程中需要使用Scipy的Minimize函数时,遇到了以下错误。

TypeError                                 Traceback (most recent call last)
E:\Anocoda\lib\site-packages\scipy\optimize\slsqp.py in _minimize_slsqp(func, x0, args, jac, bounds, constraints, maxiter, ftol, iprint, disp, eps, callback, **unknown_options)
    380             try:
--> 381                 fx = float(np.asarray(fx))
    382             except (TypeError, ValueError):

TypeError: only size-1 arrays can be converted to Python scalars

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-17-806ef2884c77> in <module>()
     30 print(x0)
     31 
---> 32 result=optimize.minimize(min_f,x0,method='SLSQP',bounds=bnds,constraints=cons)
     33 
     34 result

E:\Anocoda\lib\site-packages\scipy\optimize\_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
    609     elif meth == 'slsqp':
    610         return _minimize_slsqp(fun, x0, args, jac, bounds,
--> 611                                constraints, callback=callback, **options)
    612     elif meth == 'trust-constr':
    613         return _minimize_trustregion_constr(fun, x0, args, jac, hess, hessp,

E:\Anocoda\lib\site-packages\scipy\optimize\slsqp.py in _minimize_slsqp(func, x0, args, jac, bounds, constraints, maxiter, ftol, iprint, disp, eps, callback, **unknown_options)
    381                 fx = float(np.asarray(fx))
    382             except (TypeError, ValueError):
--> 383                 raise ValueError("Objective function must return a scalar")
    384             # Compute the constraints
    385             if cons['eq']:

ValueError: Objective function must return a scalar

代码如下

from scipy import optimize
def min_f(w):
    w=np.array(w)
    rp=np.sum(data3.mean()*500*w)
    vp=np.sqrt(np.dot(w.T, np.dot(data3.cov()*500,w)))
    return np.array([rp,vp])
cons=({'type':'eq','fun':lambda w:sum(w)-1})
bnds=tuple((0,1) for i in range(len(weights1)))#生成含有4个(0,1)的元组
x0=len(weights1)*[1/len(weights1)]
print(x0)
result=optimize.minimize(min_f,x0,method='SLSQP',bounds=bnds,constraints=cons)
result

我看了很多教程自己没有错误呀,求组

舒畅123的主页 舒畅123 | 初学一级 | 园豆:194
提问于:2022-11-16 22:53
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册