NumPy Essentials: Arrays and Math Operations
Learners will create and manipulate NumPy arrays, perform vectorised arithmetic, and understand broadcasting so they can handle numerical data efficiently.
Why NumPy Is the Foundation of ML
NumPy is the foundation under every ML library. Its superpower is vectorized math: it works on whole arrays at once in fast C code, leaving Python loops in the dust.
import numpy as np
import time
# Speed comparison: NumPy vs Python list
n = 1_000_000
python_list = list(range(n))
np_array = np.arange(n)
# Python loop (slow)
start = time.time()
result = [x * 2 for x in python_list]
print(f'Python loop: {time.time() - start:.3f}s')
# NumPy vectorised (fast)
start = time.time()
result = np_array * 2
print(f'NumPy vectorised: {time.time() - start:.4f}s')Creating NumPy Arrays
The core NumPy object is the array. Its most important trait is shape — a tuple giving the size of each dimension, like (rows, cols). The code shows how to make them.
import numpy as np
# From Python list
a = np.array([1, 2, 3, 4, 5])
print('1D array:', a, '| shape:', a.shape) # (5,)
# 2D matrix from nested list
M = np.array([[1, 2, 3], [4, 5, 6]])
print('2D matrix shape:', M.shape) # (2, 3)
# Built-in generators
zeros = np.zeros((3, 4)) # 3x4 matrix of zeros
ones = np.ones((2, 5)) # 2x5 matrix of ones
range_arr = np.arange(0, 10, 2) # [0 2 4 6 8]
linspace = np.linspace(0, 1, 5) # 5 evenly spaced points
random = np.random.randn(3, 3) # 3x3 standard normalAll lessons in this course
- Installing Anaconda and Jupyter Notebook
- NumPy Essentials: Arrays and Math Operations
- Pandas for Data Manipulation
- Visualising Data with Matplotlib and Seaborn