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 - psubtracts the pointpfrom every row ofX(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
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 pointpto each row ofX.
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.
This browser is blocking cookies for learn.floati.life, so lessons you finished here cannot open in order. Allow cookies for this site and reload.