微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

错误:Python 中未对齐的矩阵乘法

如何解决错误:Python 中未对齐的矩阵乘法

我想在 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)

Docs: Vector/matrix functions

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。