Solve the linear regression normal equations for beta
Quick Overview
Write a NumPy function that solves the ordinary least squares normal equations for the coefficient vector, given a precomputed Gram matrix and moment vector. It tests linear solves, the cost and accuracy of explicit inverses, and the conditioning of the normal equations.
Solve the linear regression normal equations for beta
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement a NumPy function that solves the ordinary least squares normal equations `XtX @ beta = Xty` for `beta`. The Gram matrix and moment vector are already computed.
```python
def solve_normal_equations(XtX: np.ndarray, Xty: np.ndarray) -> np.ndarray:
...
```
`XtX` is a float64 array of shape `(k, k)` and `Xty` is a float64 array of shape `(k,)`. The function should:
- Return an `np.ndarray` of shape `(k,)`.
- Use `np.linalg.solve(XtX, Xty)`, not `np.linalg.inv(XtX) @ Xty`.
- Not add an intercept or modify the inputs (the ones column is already folded in).
`XtX` is guaranteed to be symmetric positive definite, so no singularity handling is required.
Example (the data are `x = [0, 1, 2]` and `y = [1, 3, 5]` with an intercept column):
```python
XtX = np.array([[3.0, 3.0], [3.0, 5.0]])
Xty = np.array([9.0, 13.0])
solve_normal_equations(XtX, Xty)
# array([1., 2.]) intercept 1, slope 2
```
```hint What happens inside the solve
Think about what `np.linalg.solve` does internally and why it never needs the inverse. That reasoning matters more here than the one line of code.
```
### Constraints & Assumptions
- `XtX` has shape `(k, k)` and is symmetric positive definite.
- `Xty` has shape `(k,)`.
- Both inputs are float64 and already include the intercept term.
- The inputs must not be modified.
### What a Strong Answer Covers
- Returning `beta` with shape `(k,)` without adding an intercept or changing the inputs.
- What `np.linalg.solve` does internally to solve the system.
- Why a direct solve is cheaper and more accurate than multiplying by an explicit inverse.
- Time and space complexity in terms of `k`.
- A quick way to check the result.
### Follow-up Questions
- Why prefer a Cholesky solve when `XtX` is SPD?
- When would you avoid the normal equations entirely?
- How would you handle many different `Xty` vectors that share the same `XtX`?
Overview: Write a NumPy function that solves the ordinary least squares normal equations for the coefficient vector, given a precomputed Gram matrix and moment vector. It tests linear solves, the cost and accuracy of explicit inverses, and the conditioning of the normal equations.
Solve the linear regression normal equations for beta
General
Nov 24, 2026
easyData ScientistOtherMachine Learning
0
0
Implement a NumPy function that solves the ordinary least squares normal equations XtX @ beta = Xty for beta. The Gram matrix and moment vector are already computed.