当约束等于零时无法在 scipy 中最小化

Unable to minimze in scipy when constraint equals zero

我有两个数组,一个是金额,另一个是风险。 我想基本上最小化金额总和,同时保持风险总和相同。为此,我想将 Amount 和 Risk 与一组权重相乘(需要求解)。

from scipy.optimize import minimize
import numpy as np

#Array of Amounts
Amount = np.array([10000000,-2000000,400000000,60000000])

#Array of Risk
Risk = np.array([-10000,5000,-20000,500])

#Minimize the sum of Amounts
def Objective(weights):
    x = weights * Amount
    return np.sum(x)

#While keeping the sum of Risks constant i.e Sum of New Weighted Risk - Sum of Old weighted risk = 0
def Cons1(weights):
    x = weights*Risk
    return np.sum(x)-np.sum(Risk)
    
#Create Constraint
cons = ({'type': 'eq', 'fun':Cons1})

#Give Initial Guess 
guess = np.array([0.25,0.25,0.25,0.25])
     
#Minimize 
minimize(Objective,guess,constraints=cons)

我得到的结果是:

     fun: -2.1834331315418437e+18
     jac: array([0., 0., 0., 0.])
 message: 'Singular matrix C in LSQ subproblem'
    nfev: 18
     nit: 3
    njev: 3
  status: 6
 success: False
       x: array([ 9.32859191e+09, -4.14243499e+09, -4.78072085e+09, -6.21192636e+09])

当我在 Excel (Simplex LP) 上使用求解器时,我得到了一个可行的结果: 使用猜测权重:

解决后:

谁能告诉我我做错了什么?

正如 Erwin Kalvelagen 正确指出的那样,这是一个线性问题。 为了记录解决方案,我使用了 linprog

import numpy as np
from scipy.optimize import linprog

#Inputs into the Equation
#We want to minimize Amount and keep Risk constant

#Input Amount    
Amount=np.array([10000000,-2000000,400000000,60000000])

#Input Risk
Risk = np.array([[-10000,5000,-20000,500]])

c= Amount
A_eq = Risk
b_eq = np.sum(A_eq)
linprog(c,A_eq=A_eq,b_eq=b_eq)

我得到正确的结果:

     fun: 24500000.0
 message: 'Optimization terminated successfully.'
     nit: 2
   slack: array([], dtype=float64)
  status: 0
 success: True
       x: array([ 2.45,  0.  ,  0.  ,  0.  ])