【问题标题】:Error: not aligned matrix multiplication in Python错误:Python 中未对齐的矩阵乘法
【发布时间】:2021-05-15 19:44:42
【问题描述】:

我想使用cvxpy在python中执行以下最小二乘最小化问题:

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, x2, x3] 视为n+2-vector,而是将3-vector 视为3-vector

我尝试将.dot 替换为@,但也没有成功。如何在上面的 sum_squares 中进行矩阵乘法?

任何帮助将不胜感激!

【问题讨论】:

  • 要加入变量使用 vstack、hstack 或类似的东西。
  • @MichalAdamaszek 谢谢。我试过了,没有用。如果您有任何直觉,请向我提供有关如何解决此问题的详细答案。

标签: python matrix matrix-multiplication cvxpy


【解决方案1】:

如评论所示:

cost_func = cp.sum_squares(A .dot([x1, x2, x3]) - b)
->
cost_func = cp.sum_squares(A @ cp.hstack([x1, x2, x3]) - b)

Docs: Vector/matrix functions

【讨论】:

    猜你喜欢
    • 2012-02-03
    • 2017-01-12
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多