开发者

Getting around, numpy objects mismatch error in python

开发者 https://www.devze.com 2023-03-21 20:03 出处:网络
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 wo

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 :

Valu开发者_如何学JAVAeError: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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消