Broadcasting in Numpy

Broadcasting is one of the strongest features of Numpy, which makes it more usable. So, Broadcasting is just the concept of how Numpy will handle different shapes of the array during arithmetic operations. General Principles for broadcasting:
 
Case 1: If there is an (m,n) matrix and we need to perform any operation(+,-,*,/) with a matrix of size (1,n) then it will automatically convert the (1,n)->(m,n).
Case 2: If there is an (m,n) matrix and we need to perform any operation(+,-,*,/) with a matrix of size (m,1) then it will automatically convert the (m,1)->(m,n)
Case 3: If there is an (m,1) matrix and we need to perform any operation(+,-,*,/) with a matrix of size (1,1) then it will automatically convert the (1,1)->(m,1)
Case 4: If there is a (1,m) matrix and we need to perform any operation(+,-,*,/) with a matrix of size (1,1) then it will automatically convert the (1,1)->(1,m)
 
Now, I would like to illustrate an example which will let you know the application of broadcasting in data science. This is one of the examples which was discussed by Godfather of AI, Andrew Ng in one of his course. I hope it will make easy to understand.
 

Application of Broadcasting

## Let us consider an example in which we need to calculate the % of calories from carb, protein, fat in different foods
## Each colum represent to new food like col1-> food1(apple), col2-> food2(orange) , col3-> food3(banana) =, col4->food4(mango)
## Rows represent of as-: row1->carb ,row2->protein ,row3->fat
import numpy as np

A =np.array([[56.0,0.0,4.4,68.0],
    [1.2,104.0,52.0,8.0],
    [1.8,135.0,99.0,0.9]])
print(A)
[[ 56.    0.    4.4  68. ]
 [  1.2 104.   52.    8. ]
 [  1.8 135.   99.    0.9]]
## Matrix calculation to find out the 
## axis=0  means columnwise 
calc = A.sum(axis=0)
print(calc)
[ 59.  239.  155.4  76.9]
## Calculation of amount of percentage of carb, protein, fat present in food1, food2,food3,food4
per = 100*A/calc
print(per)
[[94.91525424  0.          2.83140283 88.42652796]
 [ 2.03389831 43.51464435 33.46203346 10.40312094]
 [ 3.05084746 56.48535565 63.70656371  1.17035111]]
print("Food1 i.e, Apple has",per[:,0])
Food1 i.e, Apple has [94.91525424  2.03389831  3.05084746]
In the above example, you are able to understand how the calc(1,4) array is dividing the A(3,4) matrix through broadcasting.

Leave a Comment

Your email address will not be published. Required fields are marked *