如何解决通过 lambda 调用函数时维度错误
我对以下代码片段有问题,我在其中优化了一个函数(最小化波动)。
from scipy import optimize as sco
import numpy as np
def risk_measure(covMatrix,weights):
risk = np.dot(weights,np.dot(covMatrix,weights))
return risk
prescribed_esg = 6 # esg score between 0 and 10 used as threshold in the esg_constraint
# Covariance and return matrix
V = np.matrix([[84.76695659,20.8854772,20.62182415,74.73652696,14.35995947],[20.8854772,35.22429277,12.95439707,32.22912903,12.96449085],[20.62182415,44.02079739,38.73627316,9.46608475],[74.73652696,178.86640813,33.40281336],[14.35995947,12.96449085,9.46608475,33.40281336,32.38514103]])
R = np.matrix([[-0.32264539,-0.08469428,1.27628749,-0.23207085,0.21012106]]).T
# Mean ESG score of each company
esgarr = np.matrix([[8.24336898,4.6373262,8.30657754,4.65406417,3.43620321]]).T
# Bounds and constraints
N = len(R) # number of instruments
bounds = ((-10,10),)*N # allow shorting,bounds of stocks
constraints = {'type': 'eq','fun': lambda weights: weights.sum() - 1}
esg_constraint = {'type': 'eq','fun': lambda weights: np.dot(weights,esgarr) - prescribed_esg}
esgmvp = sco.minimize(lambda x: risk_measure(V,x),# function to be minimized
N * [1 / N],# initial guess
bounds=bounds,# boundary conditions
constraints =[constraints,esg_constraint],# equality constraints)
)
esgmvp_weights = list(esgmvp['x'])
esgmvp_risk = esgmvp['fun']
esgmvp_esg = np.dot(esgmvp_weights,esgarr)
带有错误信息
<ipython-input-252-0d6bf5d30ccf> in risk_measure(covMatrix,weights)
3
4 def risk_measure(covMatrix,weights):
----> 5 risk = np.dot(weights,weights))
6 return risk
7
<__array_function__ internals> in dot(*args,**kwargs)
ValueError: shapes (5,) and (1,5) not aligned: 5 (dim 0) != 1 (dim 0)
如果我创建一个独立的权重矩阵,我就能得到结果
weights = np.matrix([[1,1,1]])
risk = np.dot(weights,np.dot(V,weights.T))
但这在我原来的函数中转置时不起作用。
解决方法
以下解决了它
V = np.squeeze(np.asarray(V))
esg_constraint = {'type': 'eq','fun': lambda weights: np.dot(weights,esgarr).sum() - prescribed_esg}
我也编辑了函数
def risk_measure(covMatrix,weights):
risk = np.dot(weights.T,np.dot(covMatrix,weights))
return risk
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。