Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does numpy let you add different size arrays?

Why doesn't numpy throw an error when you do something like

np.ones((5,5)) + np.ones(5)

Such addition is not clearly defined in linear algebra, and it just took me several hours to track down a bug that boiled down to this

like image 999
renato Avatar asked Oct 02 '22 04:10

renato


1 Answers

np.ones((5,5)) + np.ones(5)
np.ones((5,5)) + np.ones(4) <- This would give a error.

since np.ones(5) fit the size of each row it will to a element wise addition to each row.

That's simply how numpy works. I's is not a linear algebra module.

Here is a short example of how you could do it, this does need to be extended, with more logic and cleverness. Just a proof of concept.

import numpy as np

class myMatrixClass(np.ndarray):
    def __add__(self,val):
        if (hasattr(val, '__iter__') and self.shape != val.shape):
            print "not valid addition!"
        else:
            return super(myMatrixClass, self).__add__(val)

In [33]: A = myMatrixClass( shape=(5,5))

In [34]: A[:] = 1

In [35]: B = A + 1

In [36]: B
Out[36]:
myMatrixClass([[ 2.,  2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.,  2.]])

In [37]: C = A + np.ones(5)
not valid addition!
like image 173
M4rtini Avatar answered Oct 13 '22 12:10

M4rtini