问题描述
我想在 python 中使用 cvxpy
执行以下最小二乘最小化问题:
import numpy as np
import cvxpy as cp
# Generate the data
m = 20
n = 15
A = np.random.randn(m,n+2)
b = np.random.randn(m)
# Define and solve the CVXPY problem.
x1 = cp.Variable(1) # a single variable
x2 = cp.Variable(1) # a single variable
x3 = cp.Variable(n) # a vector of length n
cost_func = cp.sum_squares(A .dot([x1,x2,x3]) - b)
problem = cp.Problem(cp.Minimize(cost_func))
problem.solve()
我总是收到错误“形状 (20,17) 和 (3,) 未对齐:17 (dim 1) != 3 (dim 0)”。这意味着 cvx
不会将 [x1,x3]
视为 n+2-vector
,而是将 3-vector
。
我尝试用 .dot
替换 @
但也没有用。如何在上面的 sum_squares 中进行矩阵乘法?
任何帮助将不胜感激!
解决方法
如评论所示:
cost_func = cp.sum_squares(A .dot([x1,x2,x3]) - b)
->
cost_func = cp.sum_squares(A @ cp.hstack([x1,x3]) - b)