在观察级约束下最小化Python中的SSD



我试图最小化权重向量(和为1)w和新向量z = a*w之间的平方差之和,给定每个值的约束,使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]

不知道你在纠结哪一部分,但你基本上只需要在评论中写下优化问题,然后用scipy.optimize.minimize解决它。注意,约束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)

最新更新