scipy.优先使用向量和约束
感谢所有人提前的时间!
我的问题是对向量表示法中的优化施加约束。 基本上,我已经将目标函数定义为:
import numpy as np
from scipy.optimize import minimize
def main():
fake_x = np.random.random((60, 10))
results = solution(fake_x, 0.05, 0.1)
print(results)
def initial_weights(fund):
index = np.asarray(fund)
dim_index = index.shape[1]
return np.array([1/dim_index]*dim_index)
def objective(w, fund):
# calculate standard deviation vector and covariance matrix
varcov = np.cov(fund, rowvar=False)
# write down the objective function
obj_fun = 0.5 * np.log(w @ varcov @ w.T)
return obj_fun
def solution(x, lb_vol, ub_vol):
varcov = np.cov(x, rowvar=False)
w0 = initial_weights(x)
cons = [{"type": "eq", "fun": lambda w: 1 - sum(w)},
[{"type": "ineq", "fun": lambda w: w[i]} for i in range(x.shape[1])],
{"type": "ineq", "fun": lambda w: w @ varcov @ w.T}]
b1 = (0, None)
b2 = [(0, None) for _ in range(x.shape[1])]
b3 = (lb_vol, ub_vol)
bnds = (b1, *b2, b3)
res = minimize(objective, w0, bounds=bnds, args=x, constraints=cons)
return res
if __name__ == "__main__":
main()
我遇到的错误是:
x = np.clip(x, new_bounds[0], new_bounds[1])
File "<__array_function__ internals>", line 5, in clip
File line 2103, in clip
return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)
File line 58, in _wrapfunc
return bound(*args, **kwds)
File line 158, in _clip
return _clip_dep_invoke_with_casting(
File line 112, in _clip_dep_invoke_with_casting
return ufunc(*args, out=out, **kwargs)
ValueError: operands could not be broadcast together with shapes (10,) (12,) (12,)
如果我的理解正确,我认为问题在于,所得数组np.clip的大小应与w相同。我仅通过删除B1和B3以及Cons的第一个也是最后一个约束来应用非阴性约束,但我不明白如何将它们全部应用在一起。
Thanks to everyone in advance for their time!
My issue is with imposing the constraints for the optimization in vectors notation.
Basically I have already defined the objective function as:
import numpy as np
from scipy.optimize import minimize
def main():
fake_x = np.random.random((60, 10))
results = solution(fake_x, 0.05, 0.1)
print(results)
def initial_weights(fund):
index = np.asarray(fund)
dim_index = index.shape[1]
return np.array([1/dim_index]*dim_index)
def objective(w, fund):
# calculate standard deviation vector and covariance matrix
varcov = np.cov(fund, rowvar=False)
# write down the objective function
obj_fun = 0.5 * np.log(w @ varcov @ w.T)
return obj_fun
def solution(x, lb_vol, ub_vol):
varcov = np.cov(x, rowvar=False)
w0 = initial_weights(x)
cons = [{"type": "eq", "fun": lambda w: 1 - sum(w)},
[{"type": "ineq", "fun": lambda w: w[i]} for i in range(x.shape[1])],
{"type": "ineq", "fun": lambda w: w @ varcov @ w.T}]
b1 = (0, None)
b2 = [(0, None) for _ in range(x.shape[1])]
b3 = (lb_vol, ub_vol)
bnds = (b1, *b2, b3)
res = minimize(objective, w0, bounds=bnds, args=x, constraints=cons)
return res
if __name__ == "__main__":
main()
The error I get is:
x = np.clip(x, new_bounds[0], new_bounds[1])
File "<__array_function__ internals>", line 5, in clip
File line 2103, in clip
return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)
File line 58, in _wrapfunc
return bound(*args, **kwds)
File line 158, in _clip
return _clip_dep_invoke_with_casting(
File line 112, in _clip_dep_invoke_with_casting
return ufunc(*args, out=out, **kwargs)
ValueError: operands could not be broadcast together with shapes (10,) (12,) (12,)
If my understanding is correct I think the problem is that the size of the resulting array np.clip should be of the same size as w. I managed to apply only the non-negativity constraint by removing b1 and b3 as well as the first and last constraints from cons, but I don't understand how I can apply all of them together.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一些基本错误:
len(w0)= 10,len(bnds)= 12
我们可以通过:来解决此问题
我不理解
[{“ type'type”:“ ineq”, “ fun”:lambda w:w [i]}在范围内(x. shape [1])],
,所以我丢下了它。 Singleton约束应在边界中指定。现在给出了一些结果。
当然,您不应使用通用NLP求解器来解决QP。 QP应使用QP求解器求解。
A few basic errors:
len(w0) = 10, len(bnds) = 12
This we can fix by:I don't understand the purpose of
[{"type": "ineq", "fun": lambda w: w[i]} for i in range(x.shape[1])],
, so I dropped that. Singleton constraints should be specified in the bounds.Now it gives some results.
Of course, you should not use a general purpose NLP solver to solve QPs. QPs should be solved with a QP solver.