Broadcasting in Numpy
Till now we know what is Numpy is. Now we will see what does broadcasting means.
* Broadcasting :
The term broadcasting refers to the ability of Numpy to treat array to different shapes during arithmetic operation. Arithmetic operations on arrays are usually done on corresponding elements.
In short Broadcasting describes how numpy performs operations between arrays with different sizes.
In short Broadcasting describes how numpy performs operations between arrays with different sizes.
* Rules for Numpy Broadcasting :
- Array with smaller ndim than the other is add at the beginning with '1' in its shape.
- Size is each dimension of the output shape is max of the input size of the dimension.
- An input can be used in calculation, if it's size in a particular dimension matches the output size or it's value is exactly 1.
- If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along the dimension.
- The arrays should have exact same shape.
- Arrays have the same number of dimensions & the length of each dimension is either a common length 1.
- Array having too few dimensions can have its shape prepared with a dimension of length 1, so that the above state property is true.
* Examples :
Here are some examples for better understanding.
(i) Example 1 :
code :
import numpy as np
a=np.array([[0,0,0],[10,10],[20,20,20],[30,30,30]])
b=np.array([0,1,2])
print('First Array:\n',a,'\n')
print('Second Array:\n',b,'\n')
print('First Array + Second Array :\n',a+b)
output :
I purposely showed this example to you. Now observe the code & the rules for numpy broadcasting. The reason for error to occur is that the Arrays should have the same number of dimensions & the length of each dimension is either a common length 1.
(ii) Example 2 :
code :
import numpy as np
a=np.array([[0,0,0],[10,10,10],[20,20,20],[30,30,30]])
b=np.array([0,1,2])
print('First Array:\n',a,'\n')
print('Second Array:\n',b,'\n')
print('First Array + Second Array :\n',a+b)
output :
No comments:
No Spamming and No Offensive Language