python 中的 numpy 对象不匹配错误

发布于 11-25 09:01 字数 198 浏览 7 评论 0原文

我在使用 numpy 在 python 中将两个大矩阵相乘时遇到问题。

我有一个 (15,7) 矩阵,我想将它乘以它的转置,即 AT(7,15)*A(15*7) ,从数学上讲这应该可行,但我收到错误:

ValueError:形状不匹配:对象无法广播到单个形状 我在Python中使用numpy。我该如何解决这个问题,请任何人帮忙!

I'm having a problem with multiplying two big matrices in python using numpy.

I have a (15,7) matrix and I want to multipy it by its transpose, i.e. AT(7,15)*A(15*7) and mathemeticaly this should work, but I get an error :

ValueError:shape mismatch:objects cannot be broadcast to a single shape
I'm using numpy in Python. How can I get around this, anyone please help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷…雨湿花2024-12-02 09:01:27

您可能已将矩阵表示为数组。您可以使用 np.asmatrix 将它们转换为矩阵,或使用 np.dot 进行矩阵乘法:

>>> X = np.random.rand(15 * 7).reshape((15, 7))
>>> X.T * X
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (7,15) (15,7)
>>> np.dot(X.T, X).shape
(7, 7)
>>> X = np.asmatrix(X)
>>> (X.T * X).shape
(7, 7)

数组和矩阵之间的一个区别是 *< /code> 在矩阵上是矩阵乘积,而在数组上它是逐元素乘积。

You've probably represented the matrices as arrays. You can either convert them to matrices with np.asmatrix, or use np.dot to do the matrix multiplication:

>>> X = np.random.rand(15 * 7).reshape((15, 7))
>>> X.T * X
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (7,15) (15,7)
>>> np.dot(X.T, X).shape
(7, 7)
>>> X = np.asmatrix(X)
>>> (X.T * X).shape
(7, 7)

One difference between arrays and matrices is that * on a matrix is matrix product, while on an array it's an element-wise product.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文