ValueError:目标函数必须返回标量

时间:2017-05-17 05:38:59

标签: python numpy scipy

我正在使用SciPy来减少差异:

port_returns=[]
port_variance=[]
for p in range(4000):
    weights = np.random.random(5)
    weights /=np.sum(weights)
    port_returns.append(np.sum(returns.mean()*245*weights))
    port_variance.append(np.sqrt(np.dot(weights.T, np.dot(returns.cov()*245, weights))))

def min_variance(weights):
    return np.array(port_variance)

cons = {'type':'eq', 'fun':lambda x: np.sum(x)-1}    
bnds = tuple((0,1) for x in range(245))
optv = sco.minimize(min_variance, 245*[1.0/245,], method='SLSQP', 
                    bounds=bnds, constraints=cons)

我尝试运行此功能,但收到以下错误:

File "D:\Python27\lib\site-packages\scipy\optimize\_minimize.py", line 458, in minimize
  constraints, callback=callback, **options)    
File "D:\Python27\lib\site-packages\scipy\optimize\slsqp.py", line 370, in _minimize_slsqp
  raise ValueError("Objective function must return a scalar")    
ValueError: Objective function must return a scalar

如何返回标量值?

1 个答案:

答案 0 :(得分:1)

将scipy升级到v1.0。这是0.19的错误