R-Squared
How much is explained.
Our line fits well, but how well exactly? R squared answers that. It's the share of the variation in scores that the line explains. One means a perfect fit, and zero means the line is no better than just guessing the average.

- How good is the fit?
- Share of variation explained
- 1 is perfect, 0 is useless
Computing R squared
The total variation is the squared distance of each score from the mean score. The leftover variation is the sum of squared errors from the line. R squared is one minus leftover, divided by total. Run it. Zero point nine eight. Study hours explain ninety eight percent of the variation in these scores.
import numpy as np
from study import hours, scores
m, b = np.polyfit(hours, scores, 1)
pred = m * hours + b
total = ((scores - scores.mean()) ** 2).sum()
leftover = ((scores - pred) ** 2).sum()
print("R squared:", round(1 - leftover / total, 3))R squared: 0.984
Also uses study.py
import numpy as np
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8])
scores = np.array([42, 50, 53, 61, 64, 72, 74, 85])Careful with R squared
For a simple line, R squared is just the correlation, squared. A high R squared doesn't prove the model is right, or causal. And adding more features always pushes R squared up a little, even useless ones. So in machine learning, we check R squared on test data the model hasn't seen.
| key | value |
|---|---|
| R² | 1 − SSE ÷ SST |
| One feature | R² = r² |
| More features | R² always rises |
| Check | on test data |
Summary
R squared is the share of variation the model explains. Check it on new data. Next, looking at what the line misses.
Key takeaways- 1 − leftover / total
- R² = r² for one feature
- Test on unseen data