  # Python | Broadcasting with NumPy Arrays

Arrays | NumPy | Python Methods and Functions

Example —

 ` import ` ` numpy as np `   ` A ` ` = ` ` np.array ([` ` 5 ` `, ` ` 7 ` `, ` ` 3 ` `, 1 ]) `` B = np.array ([ 90 , 50 , 0 , 30 ])    # array is compatible because of the same size c = a * b  print (c) `

An example for a deeper understanding —

Let`s assume that we have a large data set, each data item is a list of parameters. In Numpy, we have a two-dimensional array where each row represents a data item and the number of rows is — this is the size of the dataset. Suppose we want to apply some kind of scaling to all of this data, each parameter gets its own scaling factor or, say, each parameter is multiplied by some factor.

Just to be clear, let`s count the calories in foods using macronutrients. Roughly speaking, the caloric portions of food are composed of fat (9 calories per gram), protein (4 cpg), and carbohydrates (4 cpg). Thus, if we list some food items (our data) and for each food item we break down their macronutrients (parameters), then we can then multiply each nutrient by its calorie content (apply scaling) to calculate the calorie breakdown for each item. nutrition. Thanks to this transformation, we can now compute all kinds of useful information. For example, what is the total number of calories present in any food, or given the breakdown of my lunch, find out how many calories I got from protein, and so on.

Let`s see a naive way to create this calculation with Numpy:

exit:

` array ([[2.4, 8.7, 31.2], [157.2, 70.8, 292] , [165.6, 95.1, 191.2], [43.2, 33, 39.2]]) `

### Algorithm:

Input data: array A with dimensions m and an array B with dimensions n

` p = max (m, n) if m   Broadcasting Rules:    Broadcasting two arrays together follow these rules:    If the arrays don`t have the same rank then prepend the shape of the lower rank array with 1s until both shapes have the same length.   The two arrays are compatible in a dimension if they have the same size in the dimension or if one of the arrays has size 1 in that dimension.   The arrays can be broadcast together iff they are compatible with all dimensions.   After broadcasting, each array behaves as if it had shape equal to the element-wise maximum of shapes of the two input arrays.   In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension.      Example # 1:  Single Dimension array           `
 ` macros ` ` = ` ` array ([` ` ` ` [` ` 0.8 ` `, ` ` 2.9 ` `, ` ` 3.9 ` `], ` ` ` ` [ ` ` 52.4 ` `, ` ` 23.6 ` `, ` ` 36.5 ` `], ` ` ` ` [` ` 55.2 ` `, ` ` 31.7 ` `, ` ` 23.9 ` `], ` ` [` ` 14.4 ` `, ` ` 11 ` `, ` ` 4.9 ` `] ` `]) `   ` # Create a new array filled with zeros ` ` # same form as macros. ` ` result ` ` = ` ` zeros_like (macros) `   ` cal_per_macro ` ` = ` array ([ ` 3 ` `, ` ` 3 ` `, ` ` 8 ` `]) `   ` # Now multiply each row of macros by ` ` # cal_per_macro. In Numpy `*` this is ` ` # element-wise multiplication between two arrays. ` ` for ` ` i ` ` in ` ` range ` ` (macros.shape [` ` 0 ` `]): ` ` result [i,:] ` ` = macros [i,:] * cal_per_macro ``   result `
 ` import ` ` numpy as np ` ` a ` ` = ` ` np.array ([` ` 17 ` `, ` ` 11 ` `, ` ` 19 ` `]) ` ` # 1x3 Dimension array ` ` print ` ` (a) ` ` b ` ` = ` ` 3 ` ` print ` ` ( b) `  ` # Broadcasting happened beacuse of ` ` # miss match in array Dimension ... ` ` c ` ` = ` ` a ` ` + ` ` b ` ` print ` ` (c) `

Output:

` [17 11 19] 3 [20 14 22] `

Example 2: two-dimensional array

 ` import ` ` numpy as np ` ` A ` ` = ` ` np.array ([[ ` ` 11 ` `, ` ` 22 ` `, ` ` 33 ` `], [` ` 10 ` `, ` ` 20 ` `, ` ` 30 ` `]]) `   ` print ` ` (A) ` `  `` b = 4 print (b)   C = A + b print (C) `

Exit:

` [[11 22 33] [10 20 30]] 4 [[15 26 37] [14 24 34]] `

Example 3:

 ` import ` ` numpy as np `   ` v ` ` = ` ` np.array ([` ` 12 ` `, ` ` 24 ` `, ` ` 36 ` `]) ` ` w ` ` = ` ` np.array ([` ` 45 ` `, ` ` 55 ` `]) `   ` # To calculate the external product, we first ` ` # change v to a 3x1 column vector ` ` # then pass it against w to get output ` ` # 3x2 form, which is the outer product of v and w ` ` print ` ` (np.reshape (v, (` ` 3 ` `, ` ` 1 ` `)) ` ` * ` ` w) `   ` X ` ` = ` ` np.array ([[` ` 12 ` `, ` ` 22 , 33 ], [ 45 , 55 , 66 ]]) ``    # x is 2x3 and v is (3,) # so they translate to 2x3 print (X + v)   # Add a vector to each column of matrix X has # shape is 2x3 and w has shape (2,) If we transpose X # then it is 3x2 and can be passed against w # to produce a 3x2 result.   # Transposing this gives the final result # Of the 2x3 form, which is a matrix. print ((xT + w) .T)   # Another solution is to change the w form to a column # 2X1 form vector we can then pass it # directly against X to get the same result. pr int (x + np.reshape (w, ( 2 , 1 )) )   # Multiply the matrix by a constant, X has the form 2x3. # Numpy treats scalars as arrays of the form (); # they can be passed together to form 2x3 . print (x * 2 ) `

Exit:

` [[4 5] [8 10] [12 15]] [[2 4 6] [5 7 9]] [[5 6 7] [9 10 11]] [[5 6 7] [9 10 11]] [[2 4 6] [8 10 12]] `

Building a 2D function -

Broadcast is also often used when displaying an image based on two-dimensional functions. If we want to define a function z = f (x, y).

Example :

` `

` import numpy as np import matplotlib.pyplot as plt   # Calculates x and y coordinates for # points on sine and cosine curves x = np.arange ( 0 , 3 * np.pi, 0.1 ) y_sin = np.sin (x) y_cos = np.cos (x)   # Plot points using matplotlib plt.plot (x, y_sin) plt.plot (x, y_cos) plt.xlabel ( `x axis label` ) plt.ylabel ( `y axis label` ) plt.title ( `Sine and Cosine` ) plt.legend ([ `Sine` , ` Cosine` ])   plt.show () `

` `

Output: 