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

在CVXPY中添加含连续矩阵乘法约束时遇DCP错误的求助

问题分析与解决方法

问题原因

你遇到的DCP错误是因为约束表达式不符合CVXPY的DCP规则:

  • 当cov是半正定矩阵时,weight.T @ cov @ weight是凸二次型;
  • cp.sqrt()是凹函数,凹函数嵌套凸函数得到的表达式既非凸也非凹,不满足DCP对约束的要求(约束必须是凸函数≤常数、凹函数≥常数这类合法形式)。

修复步骤

  1. 转换约束形式:由于平方根和右侧的10都是非负的,原约束cp.sqrt(weight.T @ cov @ weight) < 10等价于weight.T @ cov @ weight < 100。这个二次型在cov半正定的情况下是凸函数,完全符合DCP规则。
  2. 避免关键字冲突:yield是Python的保留关键字,不能用作变量名,建议改为yield_vec或其他自定义名称。

修正后的代码

import cvxpy as cp
import numpy as np

# 替换为你的实际数据
yield_vec = np.array([0.1, 0.2, 0.15, 0.08, 0.12]).reshape(5, 1)
cov = np.random.randn(5,5)
cov = cov @ cov.T  # 构造半正定协方差矩阵(模拟实际场景)

weight = cp.Variable(5)
objective = cp.Maximize(weight @ yield_vec)
constraint = [weight.T @ cov @ weight < 100]
prob = cp.Problem(objective, constraint)
prob.solve()

print("最优权重:", weight.value)
print("最优目标值:", prob.value)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:05:56