Learn / Python for AI / Lesson 1

NumPy essentials

13 min Tested on Python 3.15Updated By
In short

NumPy gives Python fast arrays of numbers. Instead of looping, you write maths on whole arrays at once — prices * 1.21 — and NumPy runs it in optimised C code. Almost every AI and data library, from pandas to PyTorch, is built on the same ideas: arrays, shapes, vectorised operations and broadcasting.

Arrays and shapes

Python
import numpy as np

scores = np.array([72, 88, 95, 61])
grid = np.array([[1, 2, 3], [4, 5, 6]])

print(scores.shape, grid.shape)
print(grid.ndim, grid.size, grid.dtype)
print(grid[1, 2], grid[:, 0])
Output
(4,) (2, 3)
2 6 int64
6 [1 4]
  • shape is the size along each dimension: (rows, columns) for a 2-D array.
  • All items share one type (dtype), which is what makes arrays fast and compact.
  • Index with [row, column]; : means "everything along this axis".

Vectorised maths

Python
import numpy as np

prices = np.array([12.5, 8.0, 30.0])
qty = np.array([2, 5, 1])

print(prices * qty)
print((prices * qty).sum())
print(np.sqrt(np.array([4, 9, 16])))
print(np.round(prices * 1.21, 2))
Output
[25. 40. 30.]
95.0
[2. 3. 4.]
[15.12  9.68 36.3 ]

Operations work element by element, with no loop in sight. On a million numbers this is typically 50–100 times faster than a Python for loop.

Broadcasting

Python
import numpy as np

sales = np.array([[10, 20, 30],
                  [40, 50, 60]])   # 2 shops x 3 products
price = np.array([1.5, 2.0, 0.5])    # one price per product

print(sales * price)
print((sales * price).sum(axis=1))  # revenue per shop
Output
[[ 15.  40.  15.]
 [ 60. 100.  30.]]
[ 70. 190.]

NumPy stretches the smaller array across the bigger one when their trailing dimensions match — here the 3 prices apply to every row. axis=1 sums across columns (per row); axis=0 sums down rows (per column).

Filtering with boolean masks

Python
import numpy as np

temps = np.array([12.1, 19.4, 23.8, 17.0, 25.3])
hot = temps > 20
print(hot)
print(temps[hot])
print(np.where(temps > 20, "hot", "mild"))
print(temps.mean().round(2), temps.max(), temps.argmax())
Output
[False False  True False  True]
[23.8 25.3]
['mild' 'mild' 'hot' 'mild' 'hot']
19.52 25.3 4

Random numbers, reproducibly

Python
import numpy as np

rng = np.random.default_rng(seed=42)
print(rng.integers(1, 7, size=5))
weights = rng.normal(loc=0, scale=1, size=(2, 3))
print(weights.shape)
Output
[1 5 4 3 3]
(2, 3)

Machine learning uses random numbers everywhere: initial model weights, shuffling data, splitting train and test sets. A fixed seed makes results repeatable.

Dot products and cosine similarity

Python
import numpy as np

def cosine(a: np.ndarray, b: np.ndarray) -> float:
    return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))

# toy 3-number "embeddings" of three sentences
cat = np.array([0.9, 0.1, 0.0])
kitten = np.array([0.8, 0.2, 0.1])
invoice = np.array([0.0, 0.1, 0.95])

print(round(cosine(cat, kitten), 3))
print(round(cosine(cat, invoice), 3))
Output
0.984
0.012

AI models turn text into embeddings: long arrays of numbers where similar meanings point in similar directions. Cosine similarity, built from a dot product (@), measures that direction. It is the heart of semantic search and RAG.

Practice

Min-max scale exam scores to the range 0–1, a common step before training a model. With scores = np.array([50, 70, 90, 100]), compute (scores - min) / (max - min), then print the scaled array and the number of students above 0.5.

Expected output:
[0.  0.4 0.8 1. ]
2
Your code

Quick check

1. What is the shape of np.array([[1, 2], [3, 4], [5, 6]])?

2. What does arr[arr > 0] return?

3. A cosine similarity close to 1 means...

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →