0
作爲實驗的不等式條件變量,我想以最小化以下目標函數:使用SciPy的以最小化給定的其它變量
的參數W1和W2由lambda表達式限定:
約束條件是下列:
我還沒有找到關於如何將多變量情況下優化如本體面SciPy的例子。如果有人可以就這個問題提供指導,我很感激。
作爲實驗的不等式條件變量,我想以最小化以下目標函數:使用SciPy的以最小化給定的其它變量
的參數W1和W2由lambda表達式限定:
約束條件是下列:
我還沒有找到關於如何將多變量情況下優化如本體面SciPy的例子。如果有人可以就這個問題提供指導,我很感激。
代碼:
import numpy as np
from scipy.optimize import minimize
def fun(x):
return np.sum(x[2:])
x0 = np.zeros(4) # lambda1, lambda 2, w1, w2
cons = ({'type': 'ineq', 'fun': lambda x: x[2] - 2 + 10 * x[0] + 3 * x[1]},
{'type': 'ineq', 'fun': lambda x: x[3] - 2 + 5 * x[0] + 5 * x[1]},
{'type': 'ineq', 'fun': lambda x: x[2]},
{'type': 'ineq', 'fun': lambda x: x[3]},
{'type': 'eq', 'fun': lambda x: x[0] + x[1] - 1})
res = minimize(fun, x0, constraints=cons)
print(res)
print(np.round(res.x, 2))
輸出:
fun: -3.3306690738754696e-16
jac: array([ 0., 0., 1., 1.])
message: 'Optimization terminated successfully.'
nfev: 7
nit: 1
njev: 1
status: 0
success: True
x: array([ 5.00000000e-01, 5.00000000e-01, -3.33066907e-16,
0.00000000e+00])
[ 0.5 0.5 -0. 0. ]
這基本上只使用來自the official docs信息。
編輯我在這裏使用了一般優化函數,但是您可能應該使用scipy.optimize.linprog,因爲這是一個LP!
我沒有檢查,但linprog使用率頗像:
from scipy.optimize import linprog
c = [0, 0, 1, 1]
A = [[-10, -3, -1, 0], [-5, -5, 0, -1]]
b = [-2, -2]
A_eq = [[1, 1, 0, 0]]
b_eq = [1]
x0_bnds = (-np.inf, -np.inf, 0, 0)
x1_bnds = (np.inf, np.inf, np.inf, np.inf)
res = linprog(c, A, b, A_eq, b_eq, bounds=list(zip(x0_bnds, x1_bnds)))
print(res)
輸出:
fun: -0.0
message: 'Optimization terminated successfully.'
nit: 4
slack: array([ 0., 3.])
status: 0
success: True
x: array([-0.14285714, 1.14285714, 0. , 0. ])
的最佳解決方案。這次真是萬分感謝。 – MLhacker