我试着得到最小的重量,更接近平均体重的总和。我目前的问题是使用SLSQP解算器,我无法找到符合目标100%的正确权重。有没有其他的解决方法可以用来解决我的问题?或者任何数学建议。请帮忙。在
我现在的数学是
**min(∑|x-mean(x)|)**
**s.t.** Aw-b=0, w>=0
**bound** 0.2'<'x<0.5
数据
^{pr2}$问题:找到最接近平均值的最小重量
Python代码:
A = np.array([[3582.000000, 3394.000000, 3356.000000, 3256.000000, 3415.000000,
3505.000000, 3442.000000, 3381.000000, 3392.000000],
[233445193.000000, 217344811.000000, 237746918.000000,
219204892.000000, 225272825.000000, 242819442.000000,
215258725.000000, 227681178.000000, 215189377.000000],
[559090945.000000, 496500751.000000, 493639029.000000,
461547877.000000, 501057960.000000, 505073223.000000,
490458632.000000, 503102998.000000, 487026744.000000]])
b = np.array([8531, 1079115532, 429386951])
n=9
def fsolveMin(A,b,n):
# The constraints: Ax = b
def cons(x):
return A.dot(x)-b
cons = ({'type':'eq','fun':cons},
{'type':'ineq','fun':lambda x:x[0]})
# The minimizing constraints: the total absolute difference between the coefficients
def fn(x):
return np.sum(np.abs(x-np.mean(x)))
# Initialize the coefficients randomly
z0 = abs(np.random.randn(len(A[1,:])))
# Set up bound
# bnds = [(0, None)]*n
# Solve the problem
sol = minimize(fn, x0 = z0, constraints = cons, method = 'SLSQP', options={'disp': True})
#expected 35%
print(sol.x)
print(A.dot(sol.x))
#print(fn(sol.x))
print(str(fsolveMin(A,b,n))+"\n\n")
为了让您了解如何使用诸如scipy的linprog这样的低级工具来实现这一点,我们必须模仿它们的标准形式:
其基本思想是:
x-mean
的临时变量)现在这个例子起作用了。在
对于你的数据,你必须小心界限。确保这个问题是可行的。这个问题本身是非常不稳定的,因为硬约束用于
Ax=b
;通常您会最小化一些范数/最小二乘法(不再是LP;QP/SOCP),并将此错误添加到目标中)!在可能需要在某个时刻将解算器从}(仅在scipy1.0之后可用)。在
method='simplex'
切换到{备选方案:
使用cvxpy,公式化要容易得多(两个变体都提到过),而且您可以免费获得一个相当好的解算器(ECOS)。在
代码:
输出:
^{pr2}$现在对于您的原始数据,,事情变得很棘手!在
您需要:
示例:
输出:
编辑
这里有一个基于SOCP的最小二乘(软约束)方法,我建议在数值稳定性方面!这种方法可以而且应该根据您的需要进行调整。它是使用前面提到的使用ECOS solver的cvxpy建模工具实现的。在
基本思路:
min(l1-norm(x - mean(x)) st. Ax=b
min(l2-norm(Ax-b) + c * l1-norm(x - mean(x)))
c
是非负权衡参数c
:Ax=b
更重要c
:x - mean(x)
更重要数据和
-50, 50
和c=1e-3
边界的示例代码和输出:输出:
这种方法将始终输出一个可行的解决方案(对于我们的任务),然后您可以决定观察到的残差,如果它对您有用的话。在
正如您所观察到的,在所有公式中,0的下限都是致命的(看看您的数据之间的巨大差异!)。在
在这里,下限为0将得到一个具有高残余误差的解。在
例如:
c=1e-7
0 / 15
输出:
首先引入一个带约束的自由变量mu:
然后引入非负变量
^{pr2}$y(i)
,其中:现在你可以最小化
现在,这是一个直接的LP(线性目标和线性约束),可以用任何LP解算器进行求解。在
相关问题 更多 >
编程相关推荐