Lesson 7 of 148 min
Vectorization and broadcasting
One line on the whole array replaces a loop, and NumPy repeats a smaller array to fit when the shapes line up on the right.
After this lesson you can replace a loop with one array expression and predict the shape of the result.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
A column from a row
In the video the column was written out by hand. Real code turns a row into a column. reshape(3, 1) asks for three rows of one number. [:, None] adds a side of one at the end. With -1, NumPy works out that side's length for you.
import numpy as np
extra = np.array([1, 2, 3])
print(extra.reshape(3, 1).shape)
print(extra[:, None].shape)
print(extra.reshape(-1, 1).shape)(3, 1) (3, 1) (3, 1)
A square table gives no error
Line up (3, 3) and (3,) on the right: three is under three, so it fits. But the row is repeated down the table, so each number goes to a column, not to a row. Nothing warns you. Look at the first row: it should get 10 everywhere. When you mean one number for each row, make it a column.
import numpy as np
table = np.array([[1, 1, 1], [5, 5, 5], [9, 9, 9]])
extra = np.array([10, 20, 30])
print((table + extra)[0])
print((table + extra[:, None])[0])[11 21 31] [11 11 11]
Time it yourself
Here is the race from the video, a million scores, to run on your own computer. timeit runs the one line 200 times and gives the average, since a single run is too short to time well. Your times will be different, and so will how many times faster the one line is.
import timeit, numpy as np
scores = np.random.default_rng(0).integers(0, 10, size=(250_000, 4))
def loop():
new = scores.copy()
for i in range(250_000):
for j in range(4):
new[i, j] = scores[i, j] + 2
one = timeit.timeit(loop, number=1)
line = timeit.timeit(lambda: scores + 2, number=200) / 200
print(f"loop {one:.3f} s, one line {line:.5f} s, {one / line:.0f} times")loop 0.152 s, one line 0.00017 s, 893 times
np.vectorize is still a loop
The name sounds right, but np.vectorize runs your function once for every number, in Python. It is handy, and it is not fast. Write the sum on the whole array instead, as in the video: scores + 2.
import numpy as np
def add_two(x):
return x + 2
slow = np.vectorize(add_two)
print(slow(np.array([7, 5, 8, 6])))[ 9 7 10 8]
The flowers, the way models want them
The video took each column's average away from every row. scikit-learn's StandardScaler does that, then divides each column by how spread out it is. Both are one line of broadcasting: a row of four, repeated down 150 rows, and never copied in memory.
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
X = load_iris().data
centred = X - X.mean(axis=0)
scaled = StandardScaler().fit_transform(X)
print(centred[0].round(2))
print((centred / X.std(axis=0))[0].round(2))
print(scaled[0].round(2))[-0.74 0.44 -2.36 -1. ] [-0.9 1.02 -1.34 -1.32] [-0.9 1.02 -1.34 -1.32]
Run on Python 3.13.3, NumPy 2.5.5 and scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson. Answer as often as you like.
1 of 2
scores has the shape (3, 4): three students, four tests. extra = np.array([1, 2, 3]) holds one number for each student. What does scores + extra do?
2 of 2
extra has one number for each test. What does this print?
import numpy as np
scores = np.array([[7, 5, 8, 6], [9, 6, 7, 8], [4, 8, 6, 5]])
extra = np.array([0, 2, 0, 1])
new = scores + extra
print(new[1])The ideas in this lesson
- Vectorization
- One line on a whole array does a loop's work, inside NumPy, hundreds of times faster.
- Broadcasting
- NumPy repeats a smaller array until its shape fits the bigger one, then adds pair by pair.
- The shape rule
- Line two shapes up on the right: each pair must be equal, or one is 1 or missing.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Hook
Here's a question. You have a million exam scores. You need to add two points to every one.
You could write a loop.
Or you could write one line of NumPy. Both give you the same numbers. So how much faster is the one line?
The scores
Keep your guess. Let's start small. Here are the exam scores of three students on four tests, in a NumPy array. Three rows and four columns, so its shape is three by four.
Next to it, a variable called extra holds the points we want to add. For now, it's two.
The loop
So, do you need a loop for this? A loop goes to one score, by its row and its column, and adds the extra points. Then it goes to the next score.
Twelve scores take twelve turns.
Now take the loop away, and the row and column numbers with it. What's left?
What's left is one line. It reads: scores plus extra.
This one line does the same work, on the whole table at once.
One line for the whole array, instead of a loop... is called vectorization.
Run it
Run it. All twelve scores come out two higher, at the same time. The first student's seven is now a nine. These are the same twelve numbers the loop made.
How much faster
Now grow the table to a million scores.
What was your guess?
Here are the two times... The loop takes about a sixth of a second.
The one line takes so little that its bar hardly moves.
Here, the one line is about a thousand times faster. On any computer, it's hundreds of times.
If you guessed "about the same", that's a natural guess. Both still do a million additions. So where does the time go?
Inside NumPy
The loop runs in Python. Python takes the numbers one by one. For each one, it does a few slow checks first.
The one line gives the whole table to NumPy. And NumPy runs its own loop, in fast code. So there is still a loop. But it runs inside NumPy, not in your code. That's vectorization.
Four numbers
One number for every score is easy. Now try four numbers: extra points for each test.
The second test gets two, and the last test gets one.
So, twelve scores plus four numbers. What comes out?
An error? Four numbers? Or a table, three by four?
Pair by pair
What does plus do with two arrays?
Start with one student's four scores, and the four extra points. Both have the same shape: just four. So NumPy adds them pair by pair. Each score meets the number in the same place. Seven and zero make seven. Five and two make seven. And so on, along the row.
The row fits
Now give those four extra points to the whole table. Extra is now one row of four numbers. Its shape is just four.
Run it... No error. The new table is three by four.
If you guessed an error, that's a natural guess: the shapes are different. But NumPy doesn't stop.
Repeated down the table
But four numbers and twelve scores... which number meets which?
NumPy repeats the row of four down the table, once for every student. Then it adds pair by pair. So every student gets two more points on test two, and one more on test four.
Repeating the smaller array to fit... is called broadcasting.
Real data
Real data for AI is laid out the same way. Each example is a row, and each measurement is a column. Here, a hundred and fifty flowers have four measurements each. Before a model learns from them, you often take each column's average away from every row.
Four averages, a hundred and fifty rows. What shape comes out?
A hundred and fifty by four. The row of averages is repeated down every row.
Line them up on the right
When two arrays have different shapes, NumPy repeats the smaller one to fit. That's broadcasting.
But when do two shapes fit? Write the two shapes one under the other. The table is three by four. The extra points are just four.
Now line them up on the right.
Four is under four. They're equal. The three has nothing under it. The row is repeated along that side. So the result is three by four.
Points for each student
Now, extra points for each student. One, two and three. Extra is now one row of three numbers.
Its shape is just three.
Line them up yourself. Does it fit?
Run it... and it stops, with an error.
NumPy's words say it couldn't make these two shapes fit.
Lined up on the right, three is under four. They're not equal, and no side is missing. So NumPy has nothing to repeat.
NumPy doesn't know that rows are students. It only sees the shapes.
A column
So what shape would let three numbers run down the side of the table?
A column.
Three rows, with a single number in each. Its shape is three by one. A plain row of three, shape just three, is not a column.
Line it up on the right. Three is under three: equal. And under the four, the column has a one.
A side that's only one long is repeated too: here, across all four tests. So the result is three by four.
Run the column
Run it. On line six, the column is written row by row, like the scores. Student one gets one more point on every test. Student three gets three more.
So here's the whole rule. Line the shapes up on the right. At each place, the two numbers must be equal. If they're not, one of them must be a one, or missing.
Two things to keep
So, two things to keep.
Work on the whole array in one line, with no loop. And before you add two arrays, line their shapes up on the right. Here's the choice you'll make again and again.
A number for each column goes in a row. A number for each row goes in a column.
The lab
That's the end of this unit. In its lab, you use these two lessons to change every picture in a stack of digits, in one line.
Close
So one line can work on a whole array, with no loop. Now try it on this lesson's page, and take the quiz. Give each student their own extra points.
You use this lesson in Lab 3: A thousand digits, no loop, which comes next.
Facts last checked on .
