NumPy Universal Functions and Broadcasting, With the Shape Rule
A ufunc runs one operation on every element with no loop from you. Broadcasting lets arrays of different shapes work together. Learn the right-aligned shape rule, read the error, and fix it.
What you will learn
- Apply ufuncs for arithmetic, exponents, logs and comparisons to whole arrays
- Combine masks with np.logical_and and summarise them with any, all and sum
- Predict a broadcast by lining shapes up from the right, and fix a shape that fails
- Use broadcasting for unit conversion, a distance table and column normalisation
Before you start
- NumPy arrays, shape and dtype
- NumPy reshape and newaxis
Think about a shop shelf with four price tags: 1, 2, 3 and 4. The shop raises every price by ten. You could walk along the shelf and change each tag by hand. Or you could give one instruction to the whole shelf, "add ten", and every tag changes together. The shelf still has four tags in the same order.
That second way is a universal function, or ufunc: one operation applied to every element, and the result has the shape you started with. The other idea in this lesson is broadcasting, which is how NumPy works with arrays of different shapes, and when it refuses to.
Your first ufuncs
import numpy as np
a = np.array([1, 2, 3, 4])
print(np.sqrt(a))
print(np.add(a, 10))
print(a + 10)
print(type(np.sqrt))
print(np.add(a, 10).dtype)
[1. 1.41421356 1.73205081 2. ]
[11 12 13 14]
[11 12 13 14]
<class 'numpy.ufunc'>
int64
a + 10 prints exactly what np.add(a, 10) prints. The + sign is the short way of writing it. Use the name or the sign, whichever reads better.
Arithmetic, position by position
a = np.array([10, 20, 30, 40])
b = np.array([3, 5, 7, 9])
print(np.add(a, b))
print(np.subtract(a, b))
print(np.multiply(a, b))
print(np.divide(a, b))
print(np.power(a, 2))
print(np.mod(a, b))
print(np.array_equal(np.add(a, b), a + b))
print(np.array_equal(np.mod(a, b), a % b))
[13 25 37 49]
[ 7 15 23 31]
[ 30 100 210 360]
[3.33333333 4. 4.28571429 4.44444444]
[ 100 400 900 1600]
[1 0 2 4]
True
True
Divide always gives decimals, even for 20 by 5, which prints as 4.. np.mod is the remainder, and % is its short form.
Exponents and logarithms
x = np.array([1, 4, 9, 16, 100])
print(np.sqrt(x))
print(np.abs(np.array([-3, 5, -7])))
print(np.exp([0, 1, 2]))
print(np.log([1, np.e, 10]))
print(np.log10([1, 10, 1000]))
print(np.log(np.exp(2.0)))
[ 1. 2. 3. 4. 10.]
[3 5 7]
[1. 2.71828183 7.3890561 ]
[0. 1. 2.30258509]
[0. 1. 3.]
2.0
np.log is the natural log, and np.log10 counts powers of ten. The last line shows that exp and log undo each other.
Comparisons make masks
scores = np.array([85, 42, 91, 67, 73])
passed = scores >= 70
print(passed)
print(scores[passed])
mask = np.logical_and(scores >= 70, scores < 90)
print(mask)
print(scores[mask])
print(np.any(scores > 90))
print(np.all(scores > 50))
print(np.sum(passed))
[ True False True False True]
[85 91 73]
[ True False False False True]
[85 73]
True
False
3
A comparison is a ufunc too. It gives one True or False per element, a mask. np.logical_and checks two conditions position by position. np.any and np.all turn a whole mask into one answer, and np.sum counts the True values, because True counts as one.
The natural thing to write is the word and:
mask = (scores >= 70) and (scores < 90)
Traceback (most recent call last):
File "S05L04_Ufuncs\and_keyword_error.py", line 5, in <module>
mask = (scores >= 70) and (scores < 90)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
and wants a single True or False, and five answers aren't one answer. Use np.logical_and (or & with brackets), which decides position by position.
Squeezing an array to one number
a = np.array([1, 2, 3, 4, 5])
print(np.sum(a))
print(np.mean(a))
print(np.std(a))
print(np.min(a))
print(np.max(a))
print(np.add.reduce(a))
print(np.add.accumulate(a))
print(np.multiply.reduce(a))
15
3.0
1.4142135623730951
1
5
15
[ 1 3 6 10 15]
120
Behind the sum, np.add.reduce puts + between every element. accumulate keeps every step on the way, a running total. Aggregation and statistics covers these in depth.
Broadcasting: one strip of wallpaper
Think about a wall and one strip of wallpaper. If the strip is exactly as tall as the wall, you don't cut it, you just repeat it across until the wall is covered. Bring a strip that's too short, and repeating it sideways doesn't help, because the height is wrong. That's broadcasting: the smaller array is repeated along a side to fit the larger one, but only when the sizes allow it.
The smallest case is a single number:
a = np.array([1, 2, 3])
print(a + 10)
print(a.shape, np.shape(10))
print(a * 2)
print(a > 1)
[11 12 13]
(3,) ()
[2 4 6]
[False True True]
A single number has shape (), no sides at all, so it fits anything. NumPy doesn't actually copy the ten in memory. It only behaves as if it did, and that's why it stays quick.
A row stretches down, a column stretches across
matrix = np.array([[1, 2, 3],
[4, 5, 6]])
row = np.array([10, 20, 30])
print(matrix.shape, row.shape)
print(matrix + row)
print((matrix + row).shape)
(2, 3) (3,)
[[11 22 33]
[14 25 36]]
(2, 3)
The shapes differ, but the last number matches, so the row is stretched downward, one copy per matrix row. Stretching works sideways too. A column of shape (2, 1) has one value per row, and its 1 is the side that can stretch:
column = np.array([[100],
[200]])
print(matrix.shape, column.shape)
print(matrix + column)
print(np.array([1, 2, 3]) + np.array([[10], [20]]))
(2, 3) (2, 1)
[[101 102 103]
[204 205 206]]
[[11 12 13]
[21 22 23]]
In the last line both sides stretch at once: the row repeats down and the column repeats across.
The rule, checked in code
Line the two shapes up from the right and compare one axis at a time. Two sizes are fine if they're the same, or if one of them is 1. This small function from the lesson checks it:
import numpy as np
def check(a, b):
for x, y in zip(reversed(a), reversed(b)):
if x == y:
print(x, y, "same")
elif x == 1 or y == 1:
print(x, y, "stretch")
else:
print(x, y, "stop")
return None
return np.broadcast_shapes(a, b)
print(check((2, 3), (3,)))
print(check((2, 3), (2, 1)))
print(check((4, 1), (3,)))
print(check((2, 3), (2,)))
3 3 same
(2, 3)
3 1 stretch
2 2 same
(2, 3)
1 3 stretch
(4, 3)
3 2 stop
None
(4, 1) against (3,) is interesting: 1 against 3 stretches, and the missing side becomes 4, so the result is (4, 3).
When broadcasting fails, fix the shape
matrix = np.array([[1, 2, 3],
[4, 5, 6]])
per_row = np.array([10, 20])
print(matrix.shape, per_row.shape)
print(matrix + per_row)
(2, 3) (2,)
Traceback (most recent call last):
File "S05L04_Ufuncs\broadcast_error.py", line 8, in <module>
print(matrix + per_row)
ValueError: operands could not be broadcast together with shapes (2,3) (2,)
You meant one value per row, but lined up from the right it's 3 against 2. The error gives both shapes, so that's the first thing to check. The fix comes straight from the rule: make it a column.
fixed = per_row.reshape(2, 1)
print(fixed.shape)
print(matrix + fixed)
print(matrix + per_row[:, np.newaxis])
(2, 1)
[[11 12 13]
[24 25 26]]
[[11 12 13]
[24 25 26]]
Broadcasting at work
Celsius to Fahrenheit
celsius = np.array([[20, 22, 19, 25, 23],
[30, 28, 32, 29, 31],
[15, 17, 14, 18, 16]])
fahr = celsius * 9 / 5 + 32
print(celsius.shape, fahr.shape)
print(fahr)
(3, 5) (3, 5)
[[68. 71.6 66.2 77. 73.4]
[86. 82.4 89.6 84.2 87.8]
[59. 62.6 57.2 64.4 60.8]]
Each single number stretches over the whole table, one step after another. One line, every cell converted.
A table of distances
points = np.array([0, 3, 7, 10])
column = points.reshape(-1, 1)
print(column.shape, points.shape)
diff = column - points
print(diff.shape)
dist = np.abs(diff)
print(dist)
(4, 1) (4,)
(4, 4)
[[ 0 3 7 10]
[ 3 0 4 7]
[ 7 4 0 3]
[10 7 3 0]]
A column of four against a row of four stretches both ways into a 4 by 4 table: every point minus every other point. The diagonal is all zeros, because each point is zero away from itself.
Normalising columns
The lesson's project also has normalize.py, which subtracts each column's mean and divides by its standard deviation, a step you'll see before training many models:
rng = np.random.default_rng(7)
data = rng.normal(50, 10, size=(100, 4))
mean = data.mean(axis=0)
std = data.std(axis=0)
print(data.shape, mean.shape, std.shape)
normalized = (data - mean) / std
print(normalized.shape)
print(normalized.mean(axis=0).round(2) + 0)
print(normalized.std(axis=0).round(2))
(100, 4) (4,) (4,)
(100, 4)
[0. 0. 0. 0.]
[1. 1. 1. 1.]
(100, 4) against (4,): the four column means stretch down all 100 rows. Afterwards every column has mean 0 and standard deviation 1.
Ufuncs against loops
import math
import timeit
import numpy as np
n = 1_000_000
values = list(range(n))
arr = np.arange(n)
def with_loop():
out = []
for v in values:
out.append(math.sqrt(v) * 2 + 1)
return out
def with_ufunc():
return np.sqrt(arr) * 2 + 1
assert np.allclose(with_loop(), with_ufunc())
loop = min(timeit.repeat(with_loop, number=1, repeat=5))
fast = min(timeit.repeat(with_ufunc, number=1, repeat=5))
ratio = loop / fast
print("same result:", True)
print("more than 5 times faster:", ratio > 5)
same result: True
more than 5 times faster: True
The file only checks "more than five times", because the exact figure changes between computers. When you read AI-generated code and see a loop over an array, ask whether a ufunc can do it.
Recap
| Idea | Remember |
|---|---|
| Ufunc | One operation on every element; +, %, > are short names for ufuncs |
| Masks | np.logical_and or &, never the word and; any, all, sum summarise |
| Broadcasting | Line shapes up from the right; each pair must match or contain a 1 |
| Fix | Reshape to (n, 1) or use np.newaxis so the sizes land on the right axis |
Try it yourself: add a row of five values to the temperature table, then try a row of four and read the error. Or ask an AI tool to explain it.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
