Weight Image Channels by a Per-Pixel Map with NumPy Broadcasting
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `weight_channels(A, W)` where `A` has shape `(h, w, c)` and `W` has shape `(h, w)`. Multiply every channel of each pixel by that pixel's weight and return an array of shape `(h, w, c)`.
- Output `[i, j, k]` equals `A[i, j, k] * W[i, j]`.
- Use broadcasting with no Python loops: reshape `W` to `(h, w, 1)` via `W[..., np.newaxis]` (or `W[:, :, None]`).
For example:
```python
A = np.ones((2, 2, 3))
W = np.array([[1., 2.],
[3., 4.]])
out = weight_channels(A, W)
out.shape # (2, 2, 3)
out[1, 0] # array([3., 3., 3.])
```
```hint Line up the shapes
Write the shape of `A` and the shape of `W` one above the other, aligned on the right, and check which axes NumPy pairs together.
```
### Constraints & Assumptions
- `A` is a numeric array of shape `(h, w, c)`.
- `W` is a numeric array of shape `(h, w)` that matches the first two axes of `A`.
- The function returns a new array and does not need to modify `A` in place.
### What a Strong Answer Covers
- The output shape and the element rule `out[i, j, k] = A[i, j, k] * W[i, j]`.
- How NumPy aligns shapes from the trailing axis and why `W` needs a trailing axis of size 1.
- A vectorized one-line implementation with no Python loops.
- Time and memory cost, including whether the weights get copied.
- Edge cases such as integer pixel dtypes and mismatched shapes.
### Follow-up Questions
- Why does `A * W` raise a `ValueError` without the extra axis, and can it ever run without raising?
- How would you extend this to a per-channel weight, with `W` of shape `(h, w, c)`?
- If the image were stored channels-first as `(c, h, w)`, what would change?
- What dtype does the result have when `A` holds `uint8` pixels, and what can go wrong?
Overview: Implement a NumPy function that multiplies every channel of an (h, w, c) image array by a per-pixel weight map of shape (h, w). It tests how broadcasting aligns array shapes and how to write vectorized array code without Python loops.