Find high-leverage observations in OLS via the hat matrix
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `high_leverage_indices(X, y)`. `X` is a NumPy array of shape `(n, k)` with no intercept column, and `y` has shape `(n,)`. Fit OLS with an intercept and return the indices of the observations whose leverage exceeds ${2(k+1)/n}$.
The leverage $h_{ii}$ of observation $i$ is the $i$-th diagonal entry of the hat matrix $H = Z(Z^\top Z)^{-1}Z^\top$, where $Z$ is `X` with a column of ones prepended.
```python
def high_leverage_indices(X: np.ndarray, y: np.ndarray) -> np.ndarray:
...
```
The function must:
- use the strict comparison $h_{ii} > 2(k+1)/n$,
- return 0-based indices sorted ascending (the order `np.flatnonzero` produces),
- return a 1-D integer `np.ndarray`, which is an empty integer array of shape `(0,)` when no observation exceeds the cutoff.
For example, with a single predictor `X = [[0], [1], [2], [3], [10]]` the cutoff is 0.8 and only the last row exceeds it, so the function returns `array([4])`.
```hint Only the diagonal matters
You never need the off-diagonal entries of H. Look for a factorization of Z under which H takes a much simpler form.
```
```hint Check your numbers
For a full-rank design with p columns, the leverage values always sum to p. Use that to test your implementation and to see where the cutoff comes from.
```
### Constraints & Assumptions
- `X` has shape `(n, k)` and no intercept column, so the fitted model has k + 1 parameters.
- `y` has shape `(n,)`. Leverage depends only on the predictors, so `y` is not used.
- Use `numpy` only.
- Assume $Z^\top Z$ is invertible.
### What a Strong Answer Covers
- Prepends the intercept column and counts k + 1 parameters in the cutoff.
- Computes the hat-matrix diagonal correctly and states the time and memory cost of the chosen method.
- Applies the strict comparison and returns ascending 0-based integer indices, including the empty `(0,)` case.
- Explains why `y` has no effect on the result and why the cutoff is twice the average leverage.
### Follow-up Questions
- How would you compute the leverage values without forming the full n×n hat matrix, and why is that more stable than inverting $Z^\top Z$?
- Why flag high leverage separately from large residuals?
- What changes if $Z^\top Z$ is singular, for example because two predictors are perfectly collinear?
- What does the rule return when n is at most 2(k+1), and what does that say about using it on small samples?
Overview: Write a NumPy function that fits OLS with an intercept, computes each observation's leverage from the diagonal of the hat matrix, and returns the indices above the 2(k+1)/n cutoff. It tests regression diagnostics, efficient linear algebra and careful handling of output types.