Complete worked example
python
import numpy as np
def inspect_example(rows, offsets):
data = np.asarray(rows, dtype=np.float64)
offsets = np.asarray(offsets, dtype=np.float64)
if data.ndim != 2 or 0 in data.shape or offsets.ndim != 1:
raise ValueError("expected a matrix and a feature vector")
if offsets.size != data.shape[1] or not np.isfinite(data).all() or not np.isfinite(offsets).all():
raise ValueError("offsets must match finite feature columns")
return data + offsets- Reasoning
- The function constructs two float64 arrays, checks rank and alignment, and evaluates data + offsets. NumPy conceptually expands the smaller shape for the operation without requiring a separately tiled input buffer. The result is still a newly computed matrix. Trace a two-by-three example: each row receives the same three column offsets, and the original row order remains unchanged. Broadcasting avoids unnecessary repeated operands, but it does not make the result free. Combining a column vector and a row vector can create a large outer-shaped result. Before accepting an expression, calculate the output shape and estimate its number of elements rather than judging only the size of each operand.