Adjusted R-Squared From Scratch
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `adjusted_r2(r2: float, n: int, p: int) -> float`, which turns an ordinary R-squared into adjusted R-squared by pure arithmetic, with no refitting of the model. `n` is the number of observations and `p` is the number of predictors excluding the intercept. Use exactly this formula:
```python
adj_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)
```
The function must meet these requirements:
- Return the result as a `float`.
- `p` excludes the intercept, so a model with an intercept and 3 features has `p = 3` and the denominator is `n - 4`.
- When `p = 0`, the result must equal `r2` exactly, so that `adjusted_r2(r2, n, 0) == r2` is `True`.
- Do not clamp. Negative values are returned as they are.
For example:
```python
adjusted_r2(0.90, n=100, p=3) # 1 - (1 - 0.90) * 99 / 96 = 0.896875
adjusted_r2(0.50, n=5, p=3) # 1 - (1 - 0.50) * 4 / 1 = -1.0 (negative)
adjusted_r2(0.80, n=50, p=0) # == 0.80 exactly
```
```hint Exactness when p = 0
Algebra says the formula collapses to `r2` when `p = 0`. Floating-point arithmetic does not always agree: try `1 - (1 - 0.1)` in Python before you rely on the formula alone for that case.
```
### Constraints & Assumptions
- Inputs are valid: `n - p - 1 != 0`, so no division-by-zero guard is needed.
- `n` and `p` are integers with `p >= 0`.
- No libraries are needed.
- Outside the `p = 0` case, the example values hold up to floating-point rounding.
### What a Strong Answer Covers
- The formula applied with `p` counting predictors only, so the residual degrees of freedom are `n - p - 1`.
- A `p = 0` result that equals `r2` exactly, with a reason the plain formula cannot promise that.
- Negative results left unclamped, and the condition under which they appear.
- What the correction factor `(n - 1) / (n - p - 1)` means in terms of degrees of freedom.
### Follow-up Questions
- Why can adjusted R-squared go negative while R-squared cannot, for OLS with an intercept?
- How does the formula change if `p` is defined to include the intercept?
- When you add one predictor to a model, under what condition does adjusted R-squared go up?
- How does adjusted R-squared compare with AIC, BIC or cross-validation for choosing between models?
Overview: Implement adjusted R-squared in Python as an arithmetic transform of R-squared, the number of observations and the number of predictors. It tests the degrees-of-freedom convention for the intercept, unclamped negative values and exact floating-point behavior when the model has no predictors.