Python Numpy Tutorial #2
In our last tutorial, we talked about numpy arrays. If you have not read it, visit here. In this post, we will deeper into numpy and talk a bit about the various tools it provides us. At first, we will see how arithmetic operations work in numpy arrays and the numpy universal functions, ending this tutorial with broadcasting.
Array Maths:
Basic element-wise addition, subtraction, multiplication, and division can be done in this way :
import numpy as np x = np.array([[1,2],[3,4]]) y = np.array([[5,6],[7,8]]) print(x+y) #element-wise addition print(x-y) #element wise subtraction print(x*y) #element-wise multiplication print(x/y) #element-wise division #For all these operations, the first operand will be from x and the second operand from y
The output will be an array of the operation on the two vectors.
The dot product of two matrices can be calculated in the following way:
import numpy as np x = np.array([[1,2],[3,4]]) y = np.array([[5,6],[7,8]]) a = x.dot(y) b = np.dot(x,y) #Both the functions produces dot/inner product between the two arrays/matrices
The cross product of the two vectors can be calculated as:
import numpy as np x = np.array([1,2]) y = np.array([5,6]) a = np.cross(x, y) #Both the functions produces cross product between the two arrays/matrices #the direction of the cross product vector is defined by the right-hand rule.
You can multiply the matrices with a scalar as :
import numpy as np x = np.array([1,2]) y = np.array([5,6]) a = x*5 print(a) #it will print [5,10] #similarly you can also add a number to each element b = y + 5; print(b) #it will print [10,11]
numpy provides a function called sum to calculate the sum of the elements of the array.
import numpy as np x = np.array([[1,2],[3,4]]) a = np.sum(x) #computes sum of all the elements of x i.e 1+2+3+4 = 10 b = np.sum(x, axis = 0) #computes sum of each coloum of x #i.e 1+3=4, 2+4=6 #the output would be [4,6] c = np.sum(x, axis = 1) #computes sum of each row of x #i.e 1+2=3, 3+4=7 #the output would be [3,7]
The transpose of a numpy array can be found by:
import numpy as np x = np.array([[1,2],[3,4]]) a = x.T print(a) #prints the transpose of x #[[1, 3] # [2, 4]]
If a matrix is invertible, the inverse can be found using :
import numpy as np x = np.array([[1,2],[3,4]]) a = np.linalg.inv(x) print(a) #since the matrix is invertible , it will print #[[-2 , 1] # [1.5, -0.5]]
In case the matrix is not invertible, it will throw np.linalg.LinAlgError. The best practice while finding the inverse of a matrix is to include a try-catch block.
import numpy as np x = np.array([[1,2],[3,4]]) try: a = np.linalg.inv(x) except np.linalg.LinAlgError: # Not invertible. Skip this one. pass else: print(a)
Numpy Array Functions:
NumPy provides familiar mathematical functions such as sin, cos, sqrt, and exp. These functions are called the universal function in numpy and the act element-wise in numpy.
import numpy as np x = np.array([[1,2],[3,4]]) a = np.sqrt(x) #finds element-wise square root b = np.exp(x) #finds element-wise exponentiation c = np.log(x) #finds element-wise logarithm d = np.sin(a) #finds element-wise sine e = np.cos(a) #finds element-wise cosine
Broadcasting:
Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Let's take an example:
import numpy as np x = np.array([[1,2,3],[4,5,6],[7,8,9]]) y = np.array([1, 2, 3]) a = x+y
What do you think will it work? If you thought that it will work, congratulations, you are right! The output would be:
[[ 2, 4, 6], [ 5, 7, 9], [ 8, 10, 12]]
This is due to broadcasting. Broadcasting two arrays follow these rules:
- If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.
- The two arrays are said to be 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 if they are compatible in 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 has size 1 and the other array has size greater than 1, the first array behaves as if it were copied along that dimension
If the rules seem too confusing, read the documentation.
With these, we finish our Numpy tutorial. In my next post, we will start learning python Scipy. Till then, Happy Learning!
Comments
Post a Comment