Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting around, numpy objects mismatch error in python

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!

like image 210
Blessed Avatar asked Dec 09 '22 07:12

Blessed


1 Answers

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.

like image 50
Fred Foo Avatar answered Dec 30 '22 09:12

Fred Foo