NUMPY:Vectorized math and broadcasting
Mastering vectorized math and broadcasting concepts and implementation.
Stay out of the Python loop
Once numbers live in an array, arithmetic applies to every element. +, -, *, /, and ** all do this. So do np.sqrt, np.exp, and np.log.
import numpy as np
km = np.array([1.2, 3.5, 8.0])
miles = km * 0.621371
print(np.round(miles, 2))
print(np.sqrt(km))
Output:
[0.75 2.17 4.97]
[1.09544512 1.87082869 2.82842712]
The same shapes subtract, multiply, and divide position by position. Different shapes are allowed only when broadcasting can stretch one of them.
The broadcasting rule
NumPy compares shapes from the right. Two axes are compatible when they are equal, or when one of them is 1.
import numpy as np
# 2 stations, 3 hours
readings = np.array([
[10, 20, 30],
[12, 22, 32],
])
offset = np.array([1, 2, 3]) # one correction per hour
print(readings + offset)
Output:
[[11 22 33]
[13 24 35]]
readings is (2, 3) and offset is (3,). From the right, 3 matches 3, and the missing axis on offset is treated as 1, so the row is reused for both stations.
A column vector is shape (2, 1), not (2,). The extra axis is what makes it broadcast down rows:
import numpy as np
readings = np.array([
[10, 20, 30],
[12, 22, 32],
])
row_boost = np.array([[100], [200]])
print(readings + row_boost)
Output:
[[110 120 130]
[212 222 232]]
When it refuses
(2, 3) and (2,) do not broadcast. The trailing 3 and the trailing 2 disagree, and neither is 1. The fix is to reshape the length-2 array to (2, 1) if you meant "one value per row".
What to notice
array * 2scales.list * 2repeats. If you see commas in the printout, you still have a list.- Compare shapes from the right before you blame the data.
np.array([100, 200])is a row.np.array([[100], [200]])is a column. The brackets decide the axis.
Try this
A grade array has shape (4, 3) — four students, three assignments. Add a bonus of [5, 0, 10] to the three assignments. Then add a per-student curve of shape (4, 1).
Next: sums, means, and the axis argument, then reshape and stack.