regarding the usage of np.all along with axis

I tried to test the usage of np.all, the test array a is

 a=array([[[ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0]], [[ 0, 0, 255], [255, 255, 255], [ 0, 0, 0], [255, 0, 0]]])
b = [255,0,255]
c = np.all(a==b,axis=1)

I got

c= array([[False, True, False], [False, False, False]], dtype=bool)

I don't understand how was TRUE in c obtained from running np.all(a==b,axis=1).

2

2 Answers

Since you are calling np.all() with axis=1, a logical AND will be performed over the first dimension i.e. all the columns (numbering starts from zero).

Your array is:

a = np.array([[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 255], [255, 0, 255], [0, 0, 0], [255, 255, 0]]])

So, the first column of a i.e. [0, 0, 0, 0] and the first element of b i.e. 255 will go through an AND operation, giving the result False. All operations are given below:

[0, 0, 0, 0] & 255 => False
[0, 0, 0, 0] & 0 => True
[0, 0, 0, 0] & 255 => False
[0, 255, 0, 255] & 255 => False
[0, 255, 0, 0] & 0 => False
[255, 255, 0, 0] & 255 => False

This will give the end result of:

[[False True False] [False False False]]

Since, you are not passing the keepdims=True parameter, the resulting list is of shape [2, 3] i.e. from [2, 4, 3] and [1, 1, 3] (see NumPy broadcasting rules), the operation is performed on index=1. Otherwise, the result would be of shape [2, 1, 3].

2

The key is understanding how b broadcasts with a.

a is (2,4,3) (I like the different dimensions).

b is (3,), which broadcasts to (1,1,3).

In [708]: a==b
Out[708]:
array([[[False, True, False], [False, True, False], [False, True, False], [False, True, False]], [[False, True, True], [ True, False, True], [False, True, False], [ True, True, False]]], dtype=bool)

The all is applied on axis=1, the size 4 one (columns in the display). The result is then (2,3) shape.

The same broadcasting and axis reduction occurs in:

In [709]: (a+b).sum(axis=1)
Out[709]:
array([[1020, 0, 1020], [1530, 255, 1530]])
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like