Python for AI Engineers · Part B · Lesson 15 of 26

NumPy for AI engineers: vectors, broadcasting and cosine similarity

NumPy for Java and JavaScript developers: arrays, dtype and shape, slicing and masks, vectorised maths, broadcasting, @ and axis, then the AI part: cosine similarity between embeddings, top-k search with argsort, seeded randomness, and float32 vs float64.

⏱ 45 min3 exercises that check your codeRuns in your browser

By the end you can

  • Create NumPy arrays, read their dtype and shape, and index, slice and filter them with boolean masks
  • Replace Python loops with vectorised maths, and predict the result shape of broadcasting
  • Use @ for matrix multiply and the axis argument for sum, mean and argmax
  • Compute cosine similarity between embeddings and run a top-k search over a matrix of them
  • Make random data reproducible with a seeded Generator, and pick float32 for embeddings to halve the memory
1 / 6

1Arrays, not lists

Every embedding, every batch of model scores and every image in AI work is a long list of numbers. A Python list can hold them, but it is slow and has the wrong maths: each item is a separate Python object, and + or * work on the list, not on the numbers.

A NumPy array (numpy.ndarray) stores numbers of one type side by side in one block of memory, like a Java double[] or a JavaScript Float64Array. Arithmetic on it applies to every element, and the loop runs in compiled C code. Install it with uv add numpy in a project from lesson 1. The boxes on this page already have it.

By convention everyone imports it as np.

Try it: edit and run
import numpy as np

prices = [0.15, 0.60, 3.00]            # a Python list
print(prices * 2)                      # list * 2 repeats the list

arr = np.array(prices)                 # copy the numbers into a NumPy array
print(arr * 2)                         # array * 2 doubles every element
print(arr + arr)                       # element by element
print(arr.sum(), arr.max())            # built-in reductions
print(type(arr).__name__, arr.dtype, arr.shape)
print(arr.tolist())                    # back to a plain Python list
Expected output
[0.15, 0.6, 3.0, 0.15, 0.6, 3.0]
[0.3 1.2 6. ]
[0.3 1.2 6. ]
3.75 3.0
ndarray float64 (3,)
[0.15, 0.6, 3.0]
JavaScript
const prices = [0.15, 0.6, 3.0];
const doubled = prices.map((p) => p * 2);  // you write the loop
const total = prices.reduce((a, b) => a + b, 0);
Java
double[] prices = {0.15, 0.6, 3.0};
double[] doubled = Arrays.stream(prices).map(p -> p * 2).toArray();
double total = Arrays.stream(prices).sum();
Python + NumPy
arr = np.array([0.15, 0.6, 3.0])
doubled = arr * 2        # no loop: applied to every element
total = arr.sum()

NumPy prints arrays without commas and drops trailing zeros, so [0.3 1.2 6. ] means the three floats 0.3, 1.2 and 6.0. dtype is the type of every element (float64 is a Java double), and shape is the size of each dimension as a tuple: (3,) is a one-dimensional array of 3 numbers. .tolist() converts back to Python numbers, which you need before json.dumps, because the json module does not know NumPy types.

Watch out prices * 2 on a list silently gives you a list twice as long, not doubled numbers. If maths on your data looks strange, check type(x): you may still have a list.

2dtype, shape and creating arrays

Real data is usually two-dimensional: a batch of 32 embeddings of 768 numbers each is one array of shape (32, 768), read as "32 rows, 768 columns". ndim is the number of dimensions and size the total number of elements.

You rarely type arrays by hand. These functions make them: np.zeros and np.ones (filled with 0.0 or 1.0), np.arange (like range), np.linspace (evenly spaced numbers between two ends), and np.array with a dtype= to choose the element type. reshape gives the same numbers a new shape, and .T transposes (rows become columns).

Try it: edit and run
import numpy as np

a = np.zeros(4)                        # four 0.0s; floats are float64 by default
b = np.ones((2, 3))                    # the shape is a tuple: 2 rows, 3 columns
c = np.arange(6)                       # 0, 1, 2, 3, 4, 5, like range(6)
d = np.linspace(0.0, 1.0, 5)           # 5 evenly spaced numbers, both ends included
e = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)

print(a, a.dtype, a.shape)
print(b.shape, b.ndim, b.size)
print(c)
print(d)
print(e)
print(e.dtype, e.shape, e.nbytes)      # 6 numbers x 4 bytes each

m = c.reshape(2, 3)                    # the same 6 numbers as 2 rows of 3
print(m)
print(m.reshape(3, -1).shape)          # -1 means "work this size out for me"
print(m.T.shape)                       # transpose: (2, 3) becomes (3, 2)
Expected output
[0. 0. 0. 0.] float64 (4,)
(2, 3) 2 6
[0 1 2 3 4 5]
[0.   0.25 0.5  0.75 1.  ]
[[1. 2. 3.]
 [4. 5. 6.]]
float32 (2, 3) 24
[[0 1 2]
 [3 4 5]]
(3, 2)
(3, 2)

The dtype=np.float32 line made 4-byte floats, so 6 of them take 24 bytes (nbytes). An array of whole numbers like c gets an integer dtype: int64 on Linux and macOS, but int32 in this browser box (Python here runs as 32-bit WebAssembly) and on Windows with NumPy 1.x. That is why the box does not print it. reshape must keep the total size: 6 numbers can be (2, 3) or (3, 2) but not (4, 2), which raises a ValueError.

Tip When something goes wrong in NumPy code, print x.shape first. Most bugs in embedding and model code are a shape that is not what you thought.

3Indexing, slicing and boolean masks

A 2-D array takes one pair of brackets with a comma: m[row, col], not m[row][col] (that also works, but makes a temporary row first). Slices work like list slices in each dimension, and : alone means "everything along this dimension", so m[:, 1] is the whole second column.

A comparison such as scores > 0.5 runs on every element and returns an array of True/False, called a mask. Indexing with a mask keeps only the elements where it is True. That is how you drop retrieved chunks below a similarity threshold in one line. Indexing with a list of positions (scores[[2, 0]]) picks those elements in that order; you will use it for top-k results.

Try it: edit and run
import numpy as np

m = np.arange(12).reshape(3, 4)        # 3 rows, 4 columns: 0..11
print(m)
print(m[1, 2])                         # row 1, column 2
print(m[0])                            # the whole first row
print(m[:, 1])                         # every row, column 1
print(m[1:, :2])                       # rows 1 and 2, columns 0 and 1
print(m[-1])                           # negative indexes count from the end

scores = np.array([0.91, 0.35, 0.78, 0.12, 0.66])   # similarity of 5 chunks
mask = scores > 0.5                    # compare every element at once
print(mask)
print(scores[mask])                    # keep only the True positions
print(np.flatnonzero(mask))            # the positions that passed
print(int(mask.sum()), "chunks pass")  # True counts as 1
print(scores[[2, 0]])                  # pick positions 2 and 0, in that order

row = m[0]                             # a slice is a VIEW of m, not a copy
row[0] = 99
print(m[0])                            # m changed too
safe = m[1].copy()                     # .copy() when you need independent data
safe[0] = -1
print(m[1])                            # unchanged
Expected output
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
6
[0 1 2 3]
[1 5 9]
[[4 5]
 [8 9]]
[ 8  9 10 11]
[ True False  True False  True]
[0.91 0.78 0.66]
[0 2 4]
3 chunks pass
[0.78 0.91]
[99  1  2  3]
[4 5 6 7]

Watch out Unlike a Python list slice, a NumPy slice shares memory with the original array, so writing to it changes the original. Call .copy() when you want separate data. Indexing with a mask or a list of positions always returns a new array.

4Vectorised maths instead of loops

"Vectorised" means you write one expression over whole arrays (arr * arr, np.sqrt(arr), arr.sum()) and NumPy runs the loop in C. A Python for loop handles every number as a separate Python object: it looks up the type, calls the right * method and allocates a new object for each result. NumPy skips all of that and walks a block of raw doubles.

The box below computes the sum of squares of 200,000 numbers both ways, takes the best of three runs for each, and prints only the comparison, because the exact times depend on your machine. On a laptop the vectorised version is usually tens of times faster. Add print(loop_s, vec_s) at the end to see your own numbers.

Try it: edit and run
import time
import numpy as np

n = 200_000
xs = list(range(n))                    # plain Python ints
arr = np.arange(n, dtype=np.float64)   # the same numbers as one float64 block


def best_of_3(fn):
    times = []
    for _ in range(3):
        start = time.perf_counter()
        result = fn()
        times.append(time.perf_counter() - start)
    return result, min(times)          # the fastest run is the least noisy


def with_loop():
    total = 0.0
    for x in xs:                       # 200,000 trips through the interpreter
        total += x * x
    return total


def vectorised():
    return float((arr * arr).sum())    # one multiply and one sum, both in C


loop_total, loop_s = best_of_3(with_loop)
vec_total, vec_s = best_of_3(vectorised)
print("same answer:", loop_total == vec_total)
print("sum of squares:", int(vec_total))
print("vectorised at least 10x faster:", vec_s * 10 < loop_s)

# the same idea for any formula: no loop in sight
x = np.array([1.0, 4.0, 9.0])
print(np.sqrt(x), np.round(np.log(x), 3), x ** 2 + 1)
Expected output
same answer: True
sum of squares: 2666646666700000
vectorised at least 10x faster: True
[1. 2. 3.] [0.    1.386 2.197] [ 2. 17. 82.]

(arr * arr).sum() first makes a new array of squares, then adds it up; for a dot product of two vectors NumPy also has arr @ arr, which does both in one step (next sections). Functions such as np.sqrt, np.log, np.exp and np.round are ufuncs (universal functions): they apply to every element, like * does. float(...) turns the NumPy result into a plain Python float.

Tip If you write for i in range(len(arr)) over a NumPy array, stop and look for the one-line vectorised form. Scoring 100,000 document embeddings against a query is a single expression, as you will see below.

5Broadcasting: when shapes do not match

Broadcasting is how NumPy combines arrays of different shapes without copying data. m * 10 is the simplest case: the scalar is stretched to every element. The same works for whole rows and columns, following three rules:

  1. Line the two shapes up from the right. A missing dimension on the left counts as 1.
  2. Two sizes fit if they are equal or one of them is 1. A size of 1 is stretched to the other size.
  3. Otherwise NumPy raises ValueError: operands could not be broadcast together.

So (2, 3) + (3,) works: line up 3 with 3, and the missing dimension counts as 1 and stretches to 2. The row is added to every row. (2, 3) * (2, 1) multiplies each row by its own number. (3, 1) + (2,) gives (3, 2): every pair, like a small multiplication table.

Try it: edit and run
import numpy as np

m = np.array([[1.0, 2.0, 3.0],
              [4.0, 5.0, 6.0]])        # shape (2, 3)

print(m * 10)                          # a scalar goes to every element

row = np.array([100.0, 200.0, 300.0])  # shape (3,)
print(m + row)                         # (2, 3) + (3,): added to each row

col = np.array([[1.0], [-1.0]])        # shape (2, 1): a column
print(m * col)                         # (2, 3) * (2, 1): row 0 x 1, row 1 x -1

a = np.array([0, 10, 20]).reshape(3, 1)   # (3, 1)
b = np.array([1, 2])                      # (2,)
print((a + b).shape)                   # (3, 1) + (2,) -> (3, 2)
print(a + b)

try:
    m + np.array([1.0, 2.0])           # (2, 3) + (2,): 3 and 2, and neither is 1
except ValueError as e:
    print("ValueError:", e)
Expected output
[[10. 20. 30.]
 [40. 50. 60.]]
[[101. 202. 303.]
 [104. 205. 306.]]
[[ 1.  2.  3.]
 [-4. -5. -6.]]
(3, 2)
[[ 1  2]
 [11 12]
 [21 22]]
ValueError: operands could not be broadcast together with shapes (2,3) (2,)

You will use broadcasting all the time in AI code: subtracting the mean of each column from a batch of embeddings (E - E.mean(axis=0)), dividing every row by its own length to normalise it (two sections down), or adding a bias vector to every row of a layer's output. When you want a column, reshape(-1, 1) turns shape (n,) into (n, 1).

Watch out Broadcasting can succeed when you did not mean it to. A (3,) array plus a (3, 1) array is not an error: it quietly builds a (3, 3) table. If a result is bigger than you expected, print the shapes of both inputs.

6Matrix multiply with @, and the axis argument

* multiplies element by element. @ is matrix multiplication: for shapes (n, k) @ (k, m) the inner sizes must match, and the result is (n, m), where each cell is the dot product of a row on the left with a column on the right. Java has no operator for this (you write three nested loops or call a library), and neither does JavaScript. A neural network layer is exactly x @ W + b.

Reductions such as sum, mean, max and argmax work on the whole array by default. Pass axis= to reduce along one dimension only: axis=0 goes down the rows and leaves one result per column, axis=1 goes across each row and leaves one result per row. The axis you name is the one that disappears from the shape. keepdims=True keeps it as a size 1, which is handy for broadcasting the result back.

The box ends with softmax, the function that turns a model's raw scores (logits) into probabilities that add up to 1. It uses everything at once: axis, keepdims and broadcasting.

Try it: edit and run
import numpy as np
np.set_printoptions(precision=3, suppress=True)   # print 3 decimals, no 1e-05 style

x = np.array([[1.0, 2.0, 3.0]])                    # (1, 3)
W = np.array([[1.0, 0.0],
              [0.0, 2.0],
              [1.0, 1.0]])                         # (3, 2)
print(x @ W)                                       # (1, 3) @ (3, 2) -> (1, 2)
print((W.T @ W).shape)                             # (2, 3) @ (3, 2) -> (2, 2)

scores = np.array([[0.2, 0.9, 0.4],                # 2 queries (rows) x 3 documents (columns)
                   [0.7, 0.1, 0.8]])
print(scores.shape)
print(scores.sum(axis=0))              # down the rows: one number per document
print(scores.mean(axis=1))             # across each row: one number per query
print(scores.argmax(axis=1))           # position of the best document for each query
print(scores.max(axis=1).shape, scores.max(axis=1, keepdims=True).shape)

logits = np.array([[2.0, 1.0, 0.1],
                   [1.0, 3.0, 0.0]])
z = logits - logits.max(axis=1, keepdims=True)     # (2, 3) - (2, 1): subtract each row's max
probs = np.exp(z) / np.exp(z).sum(axis=1, keepdims=True)
print(probs)
print(probs.sum(axis=1))                           # every row adds up to 1
Expected output
[[4. 7.]]
(2, 2)
(2, 3)
[0.9 1.  1.2]
[0.5   0.533]
[1 2]
(2,) (2, 1)
[[0.659 0.242 0.099]
 [0.114 0.844 0.042]]
[1. 1.]
Java
// (n, k) x (k, m) by hand
for (int i = 0; i < n; i++)
  for (int j = 0; j < m; j++) {
    double s = 0;
    for (int t = 0; t < k; t++) s += x[i][t] * w[t][j];
    out[i][j] = s;
  }
Python + NumPy
out = x @ w   # same result, runs in optimised C (BLAS)

np.set_printoptions(precision=3, suppress=True) only changes how arrays are printed (3 decimals, no scientific notation), not the numbers themselves. In softmax, subtracting the row maximum first does not change the answer but stops np.exp from overflowing to inf on large logits. argmax returns positions, not values: query 0 likes document 1 best, query 1 likes document 2.

7Dot product, norms and cosine similarity

An embedding is a vector of numbers that a model produces for a piece of text, so that texts with similar meaning get vectors pointing in similar directions. Real ones have 384 to 3,072 numbers; the toy ones below have 4 so you can read them.

Three pieces of maths compare two vectors a and b:

  • Dot product a @ b: multiply matching elements and add them up. Bigger means more alike, but it also grows with the vectors' lengths.
  • Norm np.linalg.norm(a): the length of the vector, the square root of the sum of squares.
  • Cosine similarity a @ b / (norm(a) * norm(b)): the dot product with the lengths divided out. It is 1.0 for the same direction, about 0 for unrelated, and -1.0 for opposite. This is the score most vector search uses.
Try it: edit and run
import numpy as np

# toy 4-number "embeddings"
cat = np.array([0.8, 0.1, 0.5, 0.2])
kitten = np.array([0.7, 0.2, 0.6, 0.1])
car = np.array([0.1, 0.9, 0.0, 0.7])


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


print(round(float(cat @ kitten), 3))         # dot product: 0.8*0.7 + 0.1*0.2 + ...
print(round(float(np.linalg.norm(cat)), 3))   # length: sqrt(0.8**2 + 0.1**2 + ...)
print(round(cosine(cat, kitten), 3))          # close to 1: similar meaning
print(round(cosine(cat, car), 3))             # much lower: different meaning
print(round(cosine(cat, cat * 3), 3))         # same direction, 3x longer: still 1.0
print(round(float(cat @ (cat * 3)), 3))       # ...but the dot product grew 3x
Expected output
0.9
0.97
0.978
0.279
1.0
2.82
JavaScript
const dot = (a, b) => a.reduce((s, x, i) => s + x * b[i], 0);
const norm = (a) => Math.sqrt(dot(a, a));
const cosine = (a, b) => dot(a, b) / (norm(a) * norm(b));
Python + NumPy
def cosine(a, b):
    return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))

round(x, 3) keeps the printed output short; the real scores have all their digits. float(...) turns the NumPy number into a Python float, so the result prints and serialises like any other number. Notice the last two lines: making a vector longer changes the dot product but not the cosine. That is why you either use cosine, or make every vector length 1 first, as the next section does.

Tip Cosine is undefined for an all-zero vector (you would divide by 0). It is rare with real embeddings, but empty or failed inputs can produce one, so check norm == 0 before dividing.

8Top-k search over a matrix of embeddings

Semantic search is: embed every document once, stack the vectors into a matrix E of shape (number of docs, dimensions), embed the question as q, score every document, and return the best k. With NumPy the scoring is one line.

First normalise: divide each row by its own length so every vector has length 1. For unit vectors the norms in the cosine formula are 1, so the dot product is the cosine. Then E @ q computes the cosine with every document at once: (5, 4) @ (4,) gives (5,), one score per document.

To rank them, np.argsort(scores) returns the positions that would sort the scores from smallest to largest; [::-1] reverses that to best first, and [:k] keeps k. Sorting a million scores to keep 5 is wasteful, so for big collections np.argpartition(scores, -k)[-k:] finds the k best positions without fully sorting (in no particular order), and you sort just those k.

Try it: edit and run
import numpy as np
np.set_printoptions(precision=3, suppress=True)

docs = ["How to reset your password",
        "Pricing and plans",
        "Cancel a subscription",
        "Reset two-factor login",
        "Office opening hours"]
E = np.array([[0.9, 0.1, 0.0, 0.3],   # one toy embedding per document
              [0.1, 0.9, 0.3, 0.0],
              [0.2, 0.7, 0.6, 0.1],
              [0.7, 0.0, 0.1, 0.6],
              [0.0, 0.2, 0.1, 0.1]])
q = np.array([0.8, 0.1, 0.1, 0.4])    # the embedding of "I forgot my password"


def normalize(x):
    return x / np.linalg.norm(x, axis=-1, keepdims=True)   # each row / its own length


E_n = normalize(E)                     # (5, 4) / (5, 1): every row now has length 1
q_n = normalize(q)                     # works on a single vector too
print(np.linalg.norm(E_n, axis=1))     # all 1.0

scores = E_n @ q_n                     # (5, 4) @ (4,) -> (5,): cosine for every doc
print(scores)

k = 3
top = np.argsort(scores)[::-1][:k]     # positions, best first
for i in top:
    print(f"{scores[i]:.3f}  {docs[i]}")

part = np.argpartition(scores, -k)[-k:]           # the k best positions, unordered
best = part[np.argsort(scores[part])[::-1]]       # sort only those k
print(best.tolist() == top.tolist())
Expected output
[1. 1. 1. 1. 1.]
[0.984 0.232 0.384 0.965 0.316]
0.984  How to reset your password
0.965  Reset two-factor login
0.384  Cancel a subscription
True

axis=-1 means "the last dimension", so the same normalize works on one vector (4,) and on a matrix (5, 4); keepdims=True keeps the lengths as a (5, 1) column so the division broadcasts one length per row. Normalise the documents once when you index them, and only the query per search.

With a real embedding model the vectors come from the API as Python lists, and one np.array call turns them into the matrix. This needs a model server, so it does not run on this page; you will build it in the semantic search lab:

import numpy as np
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
resp = client.embeddings.create(model="nomic-embed-text", input=docs)
E = np.array([d.embedding for d in resp.data], dtype=np.float32)   # (len(docs), 768)

Tip This brute-force search is exact and fast enough for up to a few hundred thousand vectors. Beyond that, vector databases (pgvector, FAISS, Qdrant) use approximate indexes, but the score they compute is the same cosine or dot product.

9Seeded randomness, memory, and float32 vs float64

For tests, demos and evals you want random data that is the same on every run. Create your own generator with rng = np.random.default_rng(seed) and call methods on it: rng.integers, rng.normal, rng.random, rng.permutation. The same seed gives the same numbers. Older code calls np.random.seed(42) and np.random.rand(), which share one hidden global state; prefer a Generator you pass around, like a java.util.Random with a fixed seed.

Memory is simple maths: elements times bytes per element. NumPy floats default to float64 (8 bytes), but embeddings do not need that precision. float32 (4 bytes, like a Java float) halves the memory and is what pgvector and FAISS store. The scores barely change.

Try it: edit and run
import numpy as np

rng = np.random.default_rng(seed=42)    # your own seeded generator
print(rng.integers(0, 10, size=5))      # 5 whole numbers from 0 to 9
print(np.round(rng.normal(size=3), 3))  # 3 numbers from a normal (bell curve) distribution

E = rng.normal(size=(1000, 384))        # 1,000 fake embeddings of 384 numbers
E /= np.linalg.norm(E, axis=1, keepdims=True)   # normalise every row in place
print(E.dtype, E.shape, E.nbytes)       # 1000 * 384 * 8 bytes

E32 = E.astype(np.float32)              # a float32 copy: 4 bytes per number
print(E32.dtype, E32.nbytes)

q = E[0]                                # use document 0 as the query
s64 = E @ q
s32 = E32 @ q.astype(np.float32)
print("largest score difference below 1e-6:", bool(np.abs(s64 - s32).max() < 1e-6))
print("same top 5:", np.argsort(s64)[::-1][:5].tolist() == np.argsort(s32)[::-1][:5].tolist())

n, d = 1_000_000, 768                   # a million chunks, 768 numbers each
print(f"float64: {n * d * 8 / 1e9:.2f} GB, float32: {n * d * 4 / 1e9:.2f} GB")

again = np.random.default_rng(seed=42)  # same seed, same numbers
print(again.integers(0, 10, size=5))
Expected output
[0 7 6 4 4]
[ 0.941 -1.951 -1.302]
float64 (1000, 384) 3072000
float32 1536000
largest score difference below 1e-6: True
same top 5: True
float64: 6.14 GB, float32: 3.07 GB
[0 7 6 4 4]

E.astype(np.float32) makes a converted copy. The two scores differ by less than one millionth and the ranking is the same, while the memory halves: about 6.1 GB of float64 for a million 768-number embeddings becomes 3.1 GB. Watch out for mixed types: E32 @ q with a float64 q quietly gives a float64 result, so convert the query too.

Watch out Calling np.random.default_rng() with no seed gives different numbers on every run. That is right for real sampling, but a test or an eval that depends on it will pass on one run and fail on the next. Pass a seed.

Common mistakes

  • Doing maths on a Python list (prices * 2 repeats the list). Convert with np.array first.
  • Writing to a slice and being surprised the original changed. NumPy slices are views; call .copy() for separate data.
  • Looping over array elements in Python instead of one vectorised expression such as E @ q.
  • Ranking by raw dot product with vectors that are not normalised, so long vectors win. Normalise rows first, or use cosine.
  • Mixing up axis=0 and axis=1. The axis you name is the one that disappears: scores.mean(axis=1) gives one value per row.
  • Keeping embeddings as float64 by default and running out of memory. Store them as float32.

Practice

Write the code, then press Check. Your work is saved in this browser.

1Cosine similarity

Write cosine_similarity(a, b) that returns the cosine similarity of two 1-D arrays as a Python float. If either vector has length 0 (all zeros), return 0.0 instead of dividing by zero. The starter returns the plain dot product, which is wrong for vectors that are not length 1.

Exercise
import numpy as np


def cosine_similarity(a, b):
    return float(a @ b)


print(cosine_similarity(np.array([1.0, 2.0]), np.array([2.0, 4.0])))
Hint

Compute `na = np.linalg.norm(a)` and `nb = np.linalg.norm(b)`. If either is 0 return 0.0, otherwise return `float(a @ b / (na * nb))`.

2Normalise every row

Write normalize_rows(E) that takes a 2-D array and returns a new array where every row has length 1. Rows that are all zeros must stay all zeros (no nan). Do it without a Python loop. The starter divides by the length of the whole matrix, which is wrong.

Exercise
import numpy as np


def normalize_rows(E):
    return E / np.linalg.norm(E)


print(normalize_rows(np.array([[3.0, 4.0], [0.0, 2.0]])))
Hint

`norms = np.linalg.norm(E, axis=1, keepdims=True)` gives a `(n, 1)` column. Replace zeros with 1 using `np.where(norms == 0, 1.0, norms)`, then return `E / norms`.

3Top-k search

Write top_k(E, q, k) that returns the positions of the k rows of E most similar to the query q by cosine similarity, best first, as a list of Python ints. The rows of E are not normalised. The starter ranks by raw dot product and returns the worst first.

Exercise
import numpy as np


def top_k(E, q, k):
    scores = E @ q
    return np.argsort(scores)[:k].tolist()


E = np.array([[1.0, 0.0], [10.0, 10.0], [0.0, 1.0]])
print(top_k(E, np.array([1.0, 0.1]), 2))
Hint

Normalise the rows of `E` and the query, compute `scores = E_n @ q_n`, then `np.argsort(scores)[::-1][:k].tolist()`.

Interview questions

Q1Why is NumPy so much faster than a Python loop?

A NumPy array stores numbers of one dtype in one contiguous block of memory, and operations on it run as compiled C loops (often using SIMD and BLAS). A Python loop handles each number as a separate object, with type checks, method lookups and an allocation for every result.

Q2What is broadcasting?

The rule NumPy uses to combine arrays of different shapes without copying: line the shapes up from the right; sizes must be equal or one of them 1, and a size of 1 (or a missing dimension) is stretched. For example (2, 3) + (3,) adds the row to each row, and (3, 1) + (2,) gives (3, 2).

Q3What is cosine similarity and why use it for embeddings?

The dot product of two vectors divided by the product of their lengths: the cosine of the angle between them, from -1 to 1. It compares direction and ignores length, and embedding models put texts with similar meaning in similar directions. If every vector is normalised to length 1, cosine equals the plain dot product, so search is one matrix multiply.

Q4How would you find the top-k most similar documents to a query with NumPy?

Normalise the document matrix once and the query per search, compute scores = E @ q for all documents at once, then np.argsort(scores)[::-1][:k]. For large collections use np.argpartition(scores, -k)[-k:] to find the k best in linear time and sort only those. Beyond a few hundred thousand vectors, move to an approximate index (FAISS, pgvector HNSW).

Q5float32 or float64 for embeddings?

float32. It halves the memory (4 bytes per number instead of 8), it is what vector databases and GPUs use, and the similarity scores change by less than a millionth, which does not change rankings in practice.

Q6What does axis mean in sum or mean?

The dimension that gets reduced and disappears from the shape. For a (queries, documents) score matrix, axis=0 goes down the rows and gives one value per document, axis=1 goes across each row and gives one value per query. keepdims=True keeps it as size 1 so the result broadcasts back against the original.