Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner workings of NumPy's logical_and.reduce

Tags:

python

numpy

I'm wondering how does np.logical_and.reduce() work.

If I look at logical_and documentation it presents it as a function with certain parameters. But when it is used with reduce it doesn't get any arguments.

When I look at reduce documentation I can see it has ufunc.reduce as it's definition. So I'm left wondering, what kind of mechanisms are used when I call np.logical_and.reduce()? What does logical_and as a ufunc represent in that snippet: a function, an object, or something else?

like image 675
Marko Avatar asked Oct 25 '25 11:10

Marko


1 Answers

I'm not sure what your question is. Using Pythons help the parameters to reduce are as shown below. reduce acts as a method of the ufunc, it's reduce that takes the arguments at run time.

In [1]: import numpy as np

help(np.logical_and.reduce)
Help on built-in function reduce:
reduce(...) method of numpy.ufunc instance
    reduce(a, axis=0, dtype=None, out=None, keepdims=False)
    Reduces `a`'s dimension by one, by applying ufunc along one axis.

Playing with this:

a=np.arange(12.0)-6.0
a.shape=3,4
a
Out[6]:
array([[-6., -5., -4., -3.],
       [-2., -1.,  0.,  1.],
       [ 2.,  3.,  4.,  5.]])

np.logical_and.reduce(a, axis=0)
Out[7]: array([ True,  True, False,  True], dtype=bool)
# False for zero in column 2

np.logical_and.reduce(a, axis=1)
Out[8]: array([ True, False,  True], dtype=bool)
# False for zero in row 1

Perhaps clearer if the dimensions are kept.

np.logical_and.reduce(a, axis=0, keepdims=True)
Out[12]: array([[ True,  True, False,  True]], dtype=bool)

np.logical_and.reduce(a, axis=1, keepdims=True)
Out[11]:
array([[ True],
       [False],    # Row 1 contains a zero.
       [ True]], dtype=bool)

The reduction ands each element along the chosen axis with the cumulative result bought forward. This is Python equivalent I'm sure numpy will be more efficient.

res=a[0]!=0     # The initial value for result bought forward
for arr in (a!=0)[1:]:
    print(res, arr)
    res = np.logical_and(res, arr)  # logical and res and a!=0
print('\nResult: ', res)

Out:
[ True  True  True  True] [ True  True False  True]
[ True  True False  True] [ True  True  True  True]

Result:  [ True  True False  True]

Hope this helps or helps clarify what your question is.

Edit: Link to Docs and callable object example.

ufunc documentation The Method documentation is about 60% down the page.

To understand a callable with methods here's a ListUfunc class to give very basic examples of numpy ufuncs for Python lists.

class ListUfunc:
    """ Create 'ufuncs' to process lists. """
    def __init__(self, func, init_reduce=0):
        self._do = func   # _do is the scalar func to apply.
        self.reduce0 = init_reduce  # The initial value for the reduction method
        # Some reductions start from zero, logical and starts from True
    def __call__(self, a, b):
        """ Apply the _do method to each pair of a and b elements. """
        res=[]
        for a_item, b_item in zip(a, b):
            res.append(self._do(a_item, b_item))
        return res

    def reduce(self, lst):
        bfwd = self.reduce0
        for item in lst:
            bfwd = self._do(bfwd, item)
        return bfwd

a=range(12)
b=range(12,24)    

plus = ListUfunc(lambda a, b : a+b)
plus(a, b)
Out[6]: [12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34]
plus.reduce(a)
Out[7]: 66
plus.reduce(b)
Out[8]: 210

log_and = ListUfunc( lambda a, b: bool(a and b), True )
log_and(a,b)
Out[25]: [False, True, True, True, True, True, True, True, True, True, True, True]
log_and.reduce(a)
Out[27]: False  # a contains a zero

log_and.reduce(b)
Out[28]: True  # b doesn't contain a zero
like image 87
Tls Chris Avatar answered Oct 27 '25 01:10

Tls Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!