You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CVXPY求解优化问题返回结果违反预设约束问题排查求助

问题排查与修复方案

核心错误原因

  • 约束条件的矩阵乘法维度错误:你定义的a是形状为(3,1)的列向量,w是形状为(1,3)的行向量,cvx.matmul(a,w)会生成3×3的矩阵,而非你需要的总重量求和值7a1 + 11a2 + 16a3。你写的约束实际要求3×3矩阵的每个元素都小于等于80,完全没有实现总重量上限的约束,因此变量可以随便取到5都满足错误的约束条件。
  • 缺失整数约束:原问题要求a1、a2、a3均为整数,但你定义cvx.Variable时没有添加integer=True参数,默认求解连续变量的优化问题。
  • *可选优化:你当前的目标函数虽然和你描述的max 0.1a1 + 0.1428a2 + 0.2a3数值上一致(通过yhat计算的结果刚好匹配),但直接写目标系数可读性更高,也能避免前面矩阵计算出错连带影响目标函数。

修复后代码

import cvxpy as cvx
import numpy as np
import scipy as sc
from scipy import linalg

#Define Starting Matrix
A1 = np.array([10,0,0])
A2 = np.array([0,7,0])
A3 = np.array([0,0,5])

#Optimal Basis and Inverse
B = np.array([A1, A2, A3])
print(f"B:{B}")
Binv = linalg.inv(B)
print(f"B-1:{Binv}")

#Define Cost Matrix
c = np.array([1, 1, 1])

#Optimal Dual Solution, y.hat
yhat = np.matmul(c,Binv)
print(f"y.hat:{yhat}")

#Pricing Problem 增加integer=True实现整数约束
a = cvx.Variable(shape=(3,1), name="a", integer=True)
w = np.array([[7,11,16]])

#Define Obj Function 也可以直接写cvx.matmul(yhat,a),效果一致
objective2 = cvx.Maximize(0.1*a[0] + (1/7)*a[1] + 0.2*a[2])

#Define Constraints 修正矩阵乘法顺序,得到总重量求和值
constraint2 = [
    cvx.matmul(w,a) <= 80,
    a >=0
]

#Define Problem and Solve
knapsack = cvx.Problem(objective2, constraint2)
solution2 = knapsack.solve()
print("最优目标值:", solution2)
print("a1、a2、a3取值:", a.value.flatten())

运行结果示例

B:[[10  0  0]
 [ 0  7  0]
 [ 0  0  5]]
B-1:[[0.1        0.         0.        ]
 [0.         0.14285714 0.        ]
 [0.         0.         0.2       ]]
y.hat:[0.1        0.14285714 0.2       ]
最优目标值: 1.1
a1、a2、a3取值: [11.  0.  0.]

*注:也可能得到[9. 0. 1.]等同最优解,目标值均为1.1

内容的提问来源于stack exchange,提问作者ewolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 15:15:05