Prerequisite : Numpy and Matplotlib

Practice questions for this tutorial

How to import numpy

import numpy as np

Importing numpy as np is an convention

How to create a numpy array

import numpy as np
x = np.array([1.0, 2.0, 4.0])
print(x)

Output

[1. 2. 4.]

Different mathematical operations in numpy (addition, subtraction, multiplication and divison) : element wise operation

import numpy as np
x = np.array([10.0, 20.0, 40.0])
y = np.array([2.0, 4.0, 10.0])
print(x+y)
print(x-y)
print(x*y)
print(x/y)

Output:

[12. 24. 50.]
[ 8. 16. 30.]
[ 20.  80. 400.]
[5. 5. 4.]

Broadcasting (Operation between numpy array and scalar)

import numpy as np
x = np.array([10.0, 20.0, 40.0])
print(x + 5.0)
print(x*2.0)

Output

[15. 25. 45.]
[20. 40. 80.]

Multidimensional numpy array

import numpy as np
x = np.array([[1,2], [3,4], [5,6]])
print("X shape: ", x.shape)
y = np.array([[2,5]])
print("y shape: ", y.shape)
xy = x*y
print("x*y = ", xy)

Output:

X shape:  (3, 2)
y shape:  (1, 2)
x*y =  [[ 2 10] 
        [ 6 20]
        [10 30]]

Convert a multi dimensional numpy array into a 1 D vector

import numpy as np
x = np.array([[1,2], [3,4], [5,6]])
print(x.flatten())

Output:

[1 2 3 4 5 6]

Access elements of a multidimensional numpy array

import numpy as np
x = np.array([[1,2], [3,4], [5,6]])
print(x[0])
print(x[1][0])

Output:

[1 2]
3

Using for loop with multi dimensional numpy array

import numpy as np
x = np.array([[1,2], [3,4], [5,6]])
for row in x:
    print(row)

Output:

[1 2]
[3 4]
[5 6]

Extracting elements from a numpy array that meet a certain criteria

import numpy as np
x = np.array([1,2,3,4,5,6,7,8,9])
print(x[x % 2 == 0])

Output:

[2 4 6 8]

This was just a quick refresher for numpy, next we will do a quick brush up on matplotlib

Creating a graph in matplotlib

import numpy as np
from matplotlib import  pyplot as plt
x = np.arange(-3.14,3.14, 0.1) # generate number between -100 to 100 with step size 0.1
y = np.sin(x)
plt.plot(x,y)
plt.show()

Plot:

Create even more advance graph

import numpy as np
from matplotlib import  pyplot as plt
x = np.arange(-3.14,3.14, 0.1) # generate number between -100 to 100 with step size 0.1

y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x,y1, label='sin')
plt.plot(x,y2, label='cos', linestyle='--')
plt.xlabel('x')
plt.ylabel('y1 & y2')
plt.title('sin and cos')
plt.legend()
plt.show()

Plot:

How to use matplotlib to load and display an image

from matplotlib import pyplot as plt
from matplotlib.image import imread
img = imread('dino.png')
plt.imshow(img)
plt.show()

Loaded image will open in a window