Vectorization

Vectorization means expressing computation as array operations instead of manual Python loops.

The goal is not to avoid loops as a rule. The goal is to let NumPy perform the numerical work on whole arrays when that makes the code clearer.

Loop version

Array version

Both compute squares. The array version says the operation directly.

Loop and vectorized versions

Runs locally with Python in your browser.

Ready to run.

Vectorize when shape is clear

Vectorized code is not automatically clearer. This is clear:

centered = values - values.mean()

It says: subtract the mean from every value.

This is not clear if the reader does not know the shapes:

scores = X @ W + b

Before writing compact array code, inspect and name the shapes.

Keep small checks

When replacing a loop with vectorized code, test on a tiny input and compare with a manual result. That habit prevents fast wrong answers.

Exercise: Vectorized square

Which expression squares every element of values when values is a NumPy array?

Answer it first, then check.

Hint

Elementwise multiplication pairs every value with the value in the same position.

Solution

Use:

values * values

Because * is elementwise for NumPy arrays, each element is multiplied by itself.