我试图最小化权重向量(总和为 1)w 和新向量 z = a*w 之间的平方差之和,给定每个 value 的约束,使得 y1 <= z <= y2。
我习惯于最小化每个变量的约束问题,而不是每个变量的不同约束。
我缺少一个明显的解决方案吗?下面是一个玩具示例,真正的问题有大约 215 个观察值。
w = np.array[0.01795054, 0.05355763, 0.16370357, 0.01856683, 0.05610746,
0.05578166, 0.17662216, 0.32852952, 0.08550193, 0.04367869]
y2 = np.array[0.0856799 , 0.04886273, 0.16629066, 0.0598285 , 0.12070527,
0.14514881, 0.17162558, 0.17162558, 0.15048137, 0.13325034]
y1 = np.array[0.01243839, 0.00860495, 0.01947604, 0.01355602, 0.0039714 ,
0.00853402, 0.00686692, 0.01595278, 0.01759997, 0.01807684]
回答1
不知道你在哪个部分苦苦挣扎,但你基本上只需要在评论中写下 optimization 的问题并用 https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html 解决它。请注意,约束 y1 <= a*w <= y2 等价于两个约束 y2 - a*w >= 0 和 -y1 + a*w >= 0:
from scipy.optimize import minimize
def objective(a):
return np.sum((a*w - w)**2)
# constraints
constrs = [
{'type': 'ineq', 'fun': lambda a: y2 - a*w},
{'type': 'ineq', 'fun': lambda a: -y1 + a*w}
]
# initial guess
x0 = np.ones(w.size)
# solve the problem: res.x contains your solution
res = minimize(objective, constraints=constrs, x0=x0)