如果我理解正确,您想建模一些优化问题并解决它。如果您对一般情况感兴趣(没有任何限制),您的问题似乎非常接近常规最小二乘误差问题(scikit-learn
例如,您可以解决)。
我建议使用cvxpy库来建模优化问题。这是对凸优化问题进行建模的便捷方式,您可以选择要在后台工作的求解器。
通过添加您提到的约束来扩展cvxpy 最小二乘示例:
# Import packages.
import cvxpy as cp
import numpy as np
# Generate data.
m = 20
n = 15
np.random.seed(1)
A = np.random.randn(m, n)
b = np.random.randn(m)
# Define and solve the CVXPY problem.
x = cp.Variable(n)
cost = cp.sum_squares(A @ x - b)
prob = cp.Problem(cp.Minimize(cost), [x>=0, cp.sum(x)==1])
prob.solve()
# Print result.
print("\nThe optimal value is", prob.value)
print("The optimal x is")
print(x.value)
print("The norm of the residual is ", cp.norm(A @ x - b, p=2).value)
在此示例中,A
(矩阵)是所有向量的矩阵,x
(变量)是权重,并且b
是已知目标。
编辑:您的数据示例:
forecasts = np.array([
[0.9, 0.91, 0.92, 0.91],
[1.1, 1.11, 1.13, 1.11],
[1.21, 1.23, 1.21, 1.23]
])
target = np.array([1.0, 1.02, 1.01, 1.04])
x = cp.Variable(forecasts.shape[0])
cost = cp.sum_squares(forecasts.T @ x - target)
prob = cp.Problem(cp.Minimize(cost), [x >= 0, cp.sum(x) == 1])
prob.solve()
print("\nThe optimal value is", prob.value)
print("The optimal x is")
print(x.value)
输出:
The optimal value is 0.0005306233766233817
The optimal x is
[ 6.52207792e-01 -1.45736370e-24 3.47792208e-01]
结果大约[0.65, 0, 0.34]
与[0.5, 0.5, 0.0]
您提到的不同,但这取决于您如何定义问题。这是最小二乘误差的解决方案。