错误:Python 中未对齐的矩阵乘法 [英] Error: not aligned matrix multiplication in Python

查看:84
本文介绍了错误:Python 中未对齐的矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to perform the following least squares minimization problem in python using 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, x2, x3] 视为 n+2-vector 而是将 3-矢量.

I am always getting the error "shapes (20,17) and (3,) not aligned: 17 (dim 1) != 3 (dim 0)". This means that cvx doesn't consider [x1, x2, x3] as a n+2-vector but a 3-vector.

我试图用 @ 替换 .dot 但也没有用.如何在上面的 sum_squares 中进行矩阵乘法?

I tried to replace .dot by @ but also didn't work. How can I do the matrix multiplication inside the sum_squares above?

任何帮助将不胜感激!

推荐答案

如评论所示:

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

请参阅文档:矢量/矩阵函数

这篇关于错误:Python 中未对齐的矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆