Add a Bias Vector to Every Row of a NumPy Matrix With Broadcasting
Quick Overview
Add a 1-D bias vector to every row of a 2-D NumPy matrix using broadcasting instead of a loop. It tests the broadcasting shape rules, result dtypes, and what happens when the bias vector has the wrong length.
Add a Bias Vector to Every Row of a NumPy Matrix With Broadcasting
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `add_bias(X, b)` that adds a 1-D bias vector `b` of shape `(m,)` to every row of a 2-D matrix `X` of shape `(n, m)`. Return a new `(n, m)` array.
Use broadcasting only: no explicit `for` loop over rows.
Example:
```python
X = np.array([[1, 2, 3],
[4, 5, 6]])
b = np.array([10, 20, 30])
add_bias(X, b)
# array([[11, 22, 33],
# [14, 25, 36]])
```
```hint Line up the shapes
Write the two shapes one above the other, aligned on the right, and check NumPy's rule for when two axis lengths are compatible.
```
### What a Strong Answer Covers
- How the broadcasting rule aligns `(n, m)` with `(m,)`, and why no loop or explicit copy of `b` is needed
- Returning a new array without modifying `X`
- The result dtype when `X` and `b` have different dtypes
- Time and memory cost of the addition
- Which wrong shapes of `b` fail with an error and which ones broadcast silently
### Follow-up Questions
- What happens if `b` has shape `(n,)` instead of `(m,)`?
- How would you add one bias value per row instead of one per column?
- How would you guard `add_bias` against a `b` whose shape broadcasts but is not what the caller meant?
- Why can `X += b` fail when `X + b` works?
Overview: Add a 1-D bias vector to every row of a 2-D NumPy matrix using broadcasting instead of a loop. It tests the broadcasting shape rules, result dtypes, and what happens when the bias vector has the wrong length.