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

Python中定义凸优化问题约束时遇维度广播错误求助

问题分析:CVXPY约束定义中的维度不匹配错误

问题代码

delta = 10
A = pandas.read_excel(r"C:\Users\mohammad\Desktop\feko1\feko\A.xlsx")
Y = pandas.read_excel(r"C:\Users\mohammad\Desktop\feko1\feko\Y.xlsx")
A = numpy.array(A)
Y = numpy.array(Y)
s_L1 = cvxpy.Variable(6561)
constraints = [cvxpy.norm(A*s_L1 - Y,2) <= delta]

其中A是2322×6561矩阵,Y是2322×1矩阵。

错误信息

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_7148\2562544661.py in <module>
----> 1 constraints = [cp.norm(A*s_L1 - Y,2) <= delta]
      2 
      
~\AppData\Roaming\Python\Python39\site-packages\cvxpy\expressions\expression.py in cast_op(self, other)
     48         """
     49         other = self.cast_to_const(other)
---> 50         return binary_op(self, other)
     51     return cast_op
     52 
~\AppData\Roaming\Python\Python39\site-packages\cvxpy\expressions\expression.py in __sub__(self, other)
    582         """Expression : The difference of two expressions.
    583         """
---> 584         return self + -other
    585 
    586     @_cast_other

~\AppData\Roaming\Python\Python39\site-packages\cvxpy\expressions\expression.py in cast_op(self, other)
     48         """
     49         other = self.cast_to_const(other)
---> 50         return binary_op(self, other)
     51     return cast_op
     52 
~\AppData\Roaming\Python\Python39\site-packages\cvxpy\expressions\expression.py in __add__(self, other)
    568             return self
    569         self, other = self.broadcast(self, other)
---> 570         return cvxtypes.add_expr()([self, other])
    571 
    572     @_cast_other

~\AppData\Roaming\Python\Python39\site-packages\cvxpy\atoms\affine\add_expr.py in __init__(self, arg_groups)
     32         # For efficiency group args as sums.
     33         self._arg_groups = arg_groups
---> 34         super(AddExpression, self).__init__(*arg_groups)
     35         self.args = []
     36         for group in arg_groups:

~\AppData\Roaming\Python\Python39\site-packages\cvxpy\atoms\atom.py in __init__(self, *args)
     49         self.args = [Atom.cast_to_const(arg) for arg in args]
     50         self.validate_arguments()
---> 51         self._shape = self.shape_from_args()
     52         if len(self._shape) > 2:
     53             raise ValueError("Atoms must be at most 2D.")

~\AppData\Roaming\Python\Python39\site-packages\cvxpy\atoms\affine\add_expr.py in shape_from_args(self)
     40         """Returns the (row, col) shape of the expression.
     41         """
---> 42         return u.shape.sum_shapes([arg.shape for arg in self.args])
     43 
     44         def expand_args(self, expr):

~\AppData\Roaming\Python\Python39\site-packages\cvxpy\utilities\shape.py in sum_shapes(shapes)
     48         # Only allow broadcasting for 0D arrays or summation of scalars.
     49         if shape != t and len(squeezed(shape)) != 0 and len(squeezed(t)) != 0:
---> 50             raise ValueError(
     51                 "Cannot broadcast dimensions " +
     52                 len(shapes)*" %s" % tuple(shapes))

ValueError: Cannot broadcast dimensions  (2322,) (2322, 1)

问题根源

错误核心是维度不匹配:

  • A*s_L1的结果是一维数组(形状(2322,)):因为s_L1定义为一维变量(cvxpy.Variable(6561)),矩阵与一维向量相乘后结果被降维。
  • Y是二维列向量(形状(2322,1)):从Excel读取并转成numpy数组后保留了原始的列向量维度。
    两者维度无法广播,导致减法操作失败。

解决方案

有两种可行的修正方式:

方式1:将Y转为一维数组

修改Y的维度,去掉多余的轴:

Y = numpy.array(Y).flatten()  # 或者使用 Y.squeeze()

方式2:将s_L1定义为二维列向量

明确指定变量为列向量形式,同时推荐用@做矩阵乘法(更符合线性代数规范):

s_L1 = cvxpy.Variable((6561, 1))  # 定义为6561行1列的变量
constraints = [cvxpy.norm(A @ s_L1 - Y, 2) <= delta]  # 使用@执行矩阵-向量乘法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:30:04