Residual Orthogonality to Design Matrix
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `def residual_orthogonality(X: np.ndarray, y: np.ndarray) -> np.ndarray`. Given `X` of shape `(n, k)` (no intercept column) and `y` of shape `(n,)`, fit OLS on `Xd = [ones, X]`, form residuals `e = y - Xd @ beta_hat`, and return `Xd^T @ e`.
The function should:
- Return a 1-D float `np.ndarray` of shape `(k+1,)`.
- Return the full vector: no norm, absolute value, or max.
- Produce entries that are about 0 up to floating-point error (around `1e-14`), not exactly 0.
Example:
```python
X = np.array([[1.0], [2.0], [3.0], [4.0]])
y = np.array([2.0, 4.1, 5.9, 8.2])
out = residual_orthogonality(X, y)
# out.shape == (2,)
# out ~= [0.0, 0.0] (each |entry| < 1e-10)
```
```hint Fitting step
NumPy has a least-squares solver that takes the design matrix directly, so you never have to form or invert `Xd^T @ Xd`.
```
```hint Checking your output
On noisy data the entries should be tiny but usually not exactly zero. Exact zeros everywhere suggest the product was never computed from the fitted residuals.
```
### Constraints & Assumptions
- `X` has shape `(n, k)` and contains no intercept column.
- `y` has shape `(n,)`.
- The output is the unreduced vector of shape `(k+1,)`, checked against a tolerance such as `1e-10`.
### What a Strong Answer Covers
- Builds `Xd = [ones, X]` with shape `(n, k+1)`.
- Fits `beta_hat` with a numerically stable least-squares solver and forms the residuals from it.
- Returns the full vector `Xd.T @ e` of shape `(k+1,)` with no reduction.
- Explains from the normal equations why the vector is zero, and what the intercept entry implies about the residuals.
- Explains why the computed entries are small but not exactly zero.
### Follow-up Questions
- Why is `Xd^T @ e` zero at the OLS solution?
- How would you compute `beta_hat` stably instead of inverting `Xd^T @ Xd`?
- If you drop the intercept column, which part of the orthogonality result still holds and which does not?
Overview: Fit ordinary least squares with an intercept in NumPy and return the product of the transposed design matrix and the residual vector. It tests the normal equations, why OLS residuals are orthogonal to every predictor and sum to zero, and how floating-point rounding shows up in the result.