【问题标题】:Getting around, numpy objects mismatch error in python四处走动,python中的numpy对象不匹配错误
【发布时间】:2011-07-19 06:35:27
【问题描述】:

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

我有一个 (15,7) 矩阵,我想将它乘以它的转置,即 AT(7,15)*A(15*7) 并且在数学上这应该可以工作,但我得到一个错误:

ValueError:shape mismatch:objects cannot be broadcast to a single shape 我在 Python 中使用 numpy。我该如何解决这个问题,请任何人帮忙!

【问题讨论】:

  • @agf:在 Numpy 中获得转置只有一种方法,而且很难出错。关于广播的错误消息足以说明问题;如果 OP 没有转置矩阵/数组,他们会得到“对象未对齐”错误,而不是这个。
  • @larsmans 谢谢,没有仔细阅读。

标签: python arrays matrix numpy mismatch


【解决方案1】:

您可能已经将矩阵表示为数组。您可以使用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)

数组和矩阵之间的一个区别是矩阵上的* 是矩阵乘积,而数组上则是元素乘积。

【讨论】:

  • 非常感谢!!拉尔斯曼它工作! asmatrix 函数有帮助,但也不知道 * 对数组和矩阵的影响。
  • 另外,在较新的(&gt;= 1.5,我认为?)版本的 numpy 数组有一个 dot 方法,所以你可以只做 X.T.dot(X) 而不是 np.dot(X.T, X)
猜你喜欢
  • 1970-01-01
  • 2010-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 2016-03-24
相关资源
最近更新 更多