使用CVXPY构建块矩阵时出现维度匹配错误的技术求助
CVXPY构建块矩阵报错的解决方法
问题背景
我在用CVXPY求解优化问题时,需要构造如下块矩阵作为约束条件:
$$M = \begin{bmatrix} Q & \mathbf{b} \ \mathbf{b}^T & 1 \end{bmatrix}$$
其中Q是CVXPY定义的对称矩阵变量,h是NumPy数组,1为标量。尝试用cp.bmat()函数构建矩阵时,代码如下:
block_matrix = cp.bmat([[Q, h.reshape(-1, 1)], [h, 1]])
触发报错:
All the input dimensions except for axis 0 must match exactly.
我已经将h通过reshape(-1,1)转为列向量,仍不清楚报错原因,完整代码如下:
import cvxpy as cp import numpy as np # Define the size of the matrix Q n = 21 # Define the variables Q = cp.Variable((n, n), symmetric=True) # Define the h vector h = np.array([0.01 * k**2 for k in range(-10, 11)]) # Form the block matrix block_matrix = cp.bmat([[Q, h.reshape(-1, 1)], [h, 1]])
报错原因
块矩阵的子块维度不匹配:
- 第一行中,
h.reshape(-1,1)是(21,1)的列向量,和Q的(21,21)矩阵拼接后,行维度都是21,列数总和为21+1=22,符合要求; - 第二行中,原代码的
h是(21,)的一维数组,CVXPY会将其视为(21,)的向量,而右侧的标量1是(1,),两者列数分别为21和1,无法在列方向拼接(需要总列数和第一行一致为22),同时行维度也不匹配(前者是21行,后者是1行)。
解决方法
需要保证块矩阵每一行的子块列数之和一致,每一列的子块行数之和一致:
- 将第二行的h转为**(1,21)的行向量**;
- 将标量1转为(1,1)的矩阵形式(或用CVXPY的常量类型)。
修正后的代码
方法一:用NumPy处理维度
import cvxpy as cp import numpy as np n = 21 Q = cp.Variable((n, n), symmetric=True) h = np.array([0.01 * k**2 for k in range(-10, 11)]) # 第二行的h转成行向量,标量1转为(1,1)矩阵 block_matrix = cp.bmat([ [Q, h.reshape(-1, 1)], [h.reshape(1, -1), np.array([[1]])] ])
方法二:用CVXPY原生函数更稳妥
import cvxpy as cp import numpy as np n = 21 Q = cp.Variable((n, n), symmetric=True) h = np.array([0.01 * k**2 for k in range(-10, 11)]) # 用cp.reshape处理向量维度,标量用cp.Constant包装 block_matrix = cp.bmat([ [Q, cp.reshape(h, (n, 1))], [cp.reshape(h, (1, n)), cp.Constant(1)] ])
内容的提问来源于stack exchange,提问作者Notwen
相关产品推荐
相关产品推荐

