一、求解二次規劃問題
min(X.T * P * X + C.T * X)
s.t.? ? Xi? > 0
? ? ? ? ?∑Xi= 1
1.定義目標函數
def objective(x):return 0.5 * np.dot(x, np.dot(P, x)) + np.dot(c, x)
2.?定義等式約束
def equality_constraint(x):return np.sum(x) - 1
3.定義邊界約束:x
# 定義邊界約束:x 每個維度取值 0-1
bounds = [(0, 1), (0, 1), (0, 1)]
4.?定義約束條件
constraint = {'type': 'eq', 'fun': equality_constraint}
5.初始猜測值
initial_guess = np.array([1/3, 1/3, 1/3])
6.求解
# 使用 minimize 函數求解
result = minimize(objective, initial_guess, method='SLSQP', bounds=bounds, constraints=constraint)# 檢查是否成功求解
if result.success:optimal_x = result.xprint(f'最優解 x* = {optimal_x}')print(f'最優目標函數值 = {result.fun}')
else:print("求解失敗:", result.message)
7.完整代碼
import numpy as np
from scipy.optimize import minimize# 定義對稱矩陣 P,每個元素大于 0
P = np.array([[2.0, 0.5, 0.3],[0.5, 3.0, 0.2],[0.3, 0.2, 4.0]])
# 定義任意向量 c
c = np.array([-1.0, -2.0, -3.0])# 定義目標函數
def objective(x):return 0.5 * np.dot(x, np.dot(P, x)) + np.dot(c, x)# 定義等式約束:x 元素之和為 1
def equality_constraint(x):return np.sum(x) - 1# 定義邊界約束:x 每個維度取值 0-1
bounds = [(0, 1), (0, 1), (0, 1)]# 定義約束條件
constraint = {'type': 'eq', 'fun': equality_constraint}# 初始猜測值
initial_guess = np.array([1/3, 1/3, 1/3])# 使用 minimize 函數求解
result = minimize(objective, initial_guess, method='SLSQP', bounds=bounds, constraints=constraint)# 檢查是否成功求解
if result.success:optimal_x = result.xprint(f'最優解 x* = {optimal_x}')print(f'最優目標函數值 = {result.fun}')
else:print("求解失敗:", result.message)