得到错误“无法将输入数组从形状(252,4)广播到形状(4)"优化中 [英] Getting an error "could not broadcast input array from shape (252,4) into shape (4)" in optimization

查看:60
本文介绍了得到错误“无法将输入数组从形状(252,4)广播到形状(4)"优化中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 python scipy 库比较陌生.我试图在下面的代码中使用 scipy.optimize 找到sharpe() 函数的最大值

I a relatively new to python scipy library. I was trying to use the scipy.optimize to find the maximum value of the sharpe() function in the following code

def sharpe(dr, wts):
    portfolio=np.ones(dr.shape[0])
    dr[0:]=wts*dr[0:]
    sharpe_ratio=-np.mean(np.sum(dr, axis=1))/np.std(np.sum(dr, axis=1))
    return sharpe_ratio

def wts_con(wts):
    return wts[0]+wts[1]+wts[2]+wts[3]-1

def sharpe_optimize(dr, sharpe_func):
    wts_guess=np.array([0.25,0.25,0.25,0.25])

    con=[{"type":"eq", "fun":wts_con}]
    bnds=((0,1),(0,1),(0,1),(0,1))

    result=spo.minimize(sharpe_func, wts_guess, args=(dr,), method="SLSQP", constraints=con, bounds=bnds, options={"disp":True})
   return result

在上面的代码中,dr 是一个 size(252,4) 数组,wts 是一个 size(4) 数组

In the above code dr is a size(252,4) array and wts is a size(4) array

当我调用sharpe_optimize() 函数时,我在第 3 行收到以下错误

I am getting the following error in line 3 when I call the sharpe_optimize() function

无法将输入数组从形状 (252,4) 广播到形状 (4)

could not broadcast input array from shape (252,4) into shape (4)

推荐答案

我认为您需要交换 sharpe 函数定义中的参数.它被定义为 sharpe(dr,wts) 但看起来你根据你对 args 的使用将最小化称为 sharpe(wts,dr)代码>.我刚刚看到上面的评论中指出了这一点!

I think you need to swap the arguments in your definition of the sharpe function. It is defined as sharpe(dr,wts) but then it looks like you call minimize as sharpe(wts,dr) based on your use of args. I have just seen that this is pointed out in the above comments!

这篇关于得到错误“无法将输入数组从形状(252,4)广播到形状(4)"优化中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆