Syllabus Lesson 12 of 246 · Module 1: Python for this course
Module 1: Python for this course

Replacing loops with whole-array maths

Why it matters Every layer of a network is a few whole-array lines. Learning to turn a loop into one line is the core NumPy skill.

Three patterns cover most of it:

  • Same operation on every item: a * 2 + 1.
  • A condition on every item: np.where(a > 0, a, 0) keeps positives and puts 0 elsewhere. np.clip(a, lo, hi) squeezes values into a range.
  • One row against many: X - p subtracts the point p from every row of X (more on why this works in Module 2).

Tiny numbers

X = np.array([[0, 0], [3, 4], [6, 8]])
p = np.array([0, 0])
np.sqrt(((X - p) ** 2).sum(axis=1))   # [ 0.  5. 10.]  distance of each row from p

Recap Describe what happens to one item, then write it once for the whole array.

Words and symbols in this lesson
array
a NumPy block of numbers, all the same type, that does maths on every item at once
axis
which direction an operation runs along: axis=0 down the rows, axis=1 along each row
Your turn

Rewrite these three loop functions with no Python loops:

  • relu(a): each value, or 0 if it is negative.
  • clip01(a): each value squeezed into the range 0 to 1.
  • distances(X, p): the straight-line distance from point p to each row of X.

Spotted a problem in this lesson? Report it · Ask about this lesson

This exercise opens soon

Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.