Compute the hat matrix for linear regression with an intercept
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement a NumPy function that returns the hat matrix of an ordinary least squares fit with an intercept.
```python
def hat_matrix(X: np.ndarray) -> np.ndarray:
...
```
`X` is a float array of shape `(n, k)` with no intercept column. Prepend a ones column to form `Xd` of shape `(n, k+1)` and return the full hat matrix $H = X_d (X_d^\top X_d)^{-1} X_d^\top$ as a float `np.ndarray` of shape `(n, n)`. Return the full matrix, not the leverages or the fitted values.
Example:
```python
X = np.array([[1.0], [2.0], [3.0]]) # shape (3, 1)
H = hat_matrix(X)
# H.shape == (3, 3), symmetric, idempotent (H @ H ≈ H)
# trace(H) ≈ 2 (== number of columns in Xd)
# H ≈ [[ 0.8333, 0.3333, -0.1667],
# [ 0.3333, 0.3333, 0.3333],
# [-0.1667, 0.3333, 0.8333]]
```
```hint Avoid the explicit inverse
You never need $(X_d^\top X_d)^{-1}$ on its own. Look for the part of the formula that can be computed as the solution of one linear system with several right-hand sides.
```
```hint Check your result
On the small example, test the properties a projection must have before you trust the code: symmetry, `H @ H ≈ H`, and the trace.
```
### Constraints & Assumptions
- `X` is a float array of shape `(n, k)` and does not include an intercept column.
- `Xd` (with the intercept column) has full column rank, so `XdᵀXd` is invertible and no rank-deficiency handling is required.
- The output is a dense `(n, n)` array.
### What a Strong Answer Covers
- Building `Xd` with the intercept column first and returning the full `(n, n)` matrix.
- Computing `H` without forming an explicit inverse, or explaining the cost of doing so.
- Checking the defining properties of `H` (symmetry, idempotence, trace) and why they hold.
- Time and memory cost, and how `n²` storage limits the size of input this can handle.
- What the diagonal of `H` says about individual observations.
### Follow-up Questions
- Why is `solve` preferred over explicitly forming `inv(XdᵀXd)`?
- What key properties should `H` satisfy, and how do they relate to the fit?
- How would you get only the leverages for a dataset with millions of rows, where the full `H` does not fit in memory?
Overview: Implement a NumPy function that adds an intercept column to a predictor matrix and returns the full hat matrix of an ordinary least squares fit. It tests projection matrices, numerically stable linear solves, and the symmetry, idempotence and trace properties of the hat matrix.