Compute regression leverage scores with an economy QR factorization
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `leverage_via_qr(X)`. Given a float array `X` of shape `(n, k)` with no intercept column (n much larger than k), prepend a ones column to form `Xd` and return the hat-matrix diagonal, the leverage values $h_{ii}$, without materializing the `(n, n)` hat matrix.
```python
def leverage_via_qr(X: np.ndarray) -> np.ndarray:
...
```
Requirements:
- `Xd` has shape `(n, k+1)`, with the ones column first.
- Use `np.linalg.qr(Xd, mode='reduced')` to get `Q` of shape `(n, k+1)`.
- Return the squared row norms of `Q`, $h_{ii} = \sum_j Q_{ij}^2$, as a 1-D float `np.ndarray` of shape `(n,)`.
- Do not form $H = X_d(X_d^\top X_d)^{-1}X_d^\top$ or any `(n, n)` matrix. Memory should stay at O(nk).
```python
X = np.array([[1.0], [2.0], [3.0], [4.0]])
h = leverage_via_qr(X) # approximately [0.7, 0.3, 0.3, 0.7], shape (4,)
# h.sum() is k + 1 = 2 up to rounding (leverage values sum to the number of columns of Xd)
# each value satisfies 0 <= h_ii <= 1
```
```hint Why the row norms
Write H in terms of Q and R and simplify using the fact that Q has orthonormal columns. That shows both why the row norms are the answer and what the argument assumes about Xd.
```
### Constraints & Assumptions
- `X` is a float array of shape `(n, k)` with no intercept column, and n is much larger than k.
- No `(n, n)` array may be created at any point, so memory stays linear in n.
- Use `numpy` only.
### What a Strong Answer Covers
- Builds `Xd` with a leading ones column and uses the reduced QR, so `Q` has shape `(n, k+1)`.
- Explains why $QQ^\top$ equals the hat matrix and why its diagonal is the squared row norms of `Q`.
- States the time and memory cost and confirms that no `(n, n)` intermediate is created.
- Notes the full-column-rank assumption the QR argument relies on and what breaks without it.
### Follow-up Questions
- Why is QR preferred over $(X_d^\top X_d)^{-1}$ here?
- How would you verify the result quickly?
- If `X` is too large to hold in memory at once, how would you still compute every leverage value?
Overview: Write a NumPy function that computes the leverage of every row in a regression design with an intercept from an economy QR factorization, so the n by n hat matrix is never built. It tests why the squared row norms of Q equal the hat diagonal, numerical stability and memory limits.