scipy 使用向量和约束条件进行方案优化

crcmnpdw  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(180)

提前感谢大家的参与!
我的问题是用向量符号来施加优化的约束条件。基本上我已经将目标函数定义为:

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的大小相同。我设法通过从cons中删除b1和b3以及第一个和最后一个约束来仅应用非负性约束,但我不明白如何将它们一起应用。

h9a6wy2h

h9a6wy2h1#

几个基本错误:

  1. len(w0) = 10, len(bnds) = 12我们可以通过以下方法解决此问题:
b2 = [(0, None) for _ in range(x.shape[1]-1)]
 b3 = (lb_vol, ub_vol)
 bnds = [*b2, b3]

1.我不明白[{"type": "ineq", "fun": lambda w: w[i]} for i in range(x.shape[1])],的用途,所以我放弃了它。单一约束应该在边界中指定。
现在它给出了一些结果。
当然,你不应该用一个通用的NLP求解器来求解QP。QP应该用QP求解器来求解。

相关问题