R squared and constant target
Quick answer
R squared compares squared prediction error with the squared deviation of the observed targets from their evaluation-set mean. It can be negative, and constant targets require an explicit policy. Static examples tested locally with Python 3.13.5, scikit-learn 1.8.0 SciPy 1.17.0 and NumPy 2.3.5 where imported. ByteMind package execution is unverified.
Negative R squared
from sklearn.metrics import r2_scorey=[1,3];print(r2_score(y,[2,2]),r2_score(y,[-1,5]))Observed local output:
0.0 -3.0The second SSE is 8 compared with SST=2.
How it works
R² = 1 - SSE/SST, where SSE = sum((y-p)²) and SST = sum((y-mean(y))²). A perfect fit yields 1 for a nonconstant target; the evaluation mean gives 0; worse predictions give a negative value. The evaluation mean is a mathematical reference, not a deployable baseline fitted on future truth. A training-mean baseline may score below zero on shifted test data. R² is not generally the squared Pearson correlation between predictions and truth; a biased prediction can have perfect correlation and poor R². For constant y, SST=0: raw R² is NaN for perfect prediction and negative infinity otherwise. The scikit-learn finite policy maps these to 1 and 0 by default; force_finite=False exposes raw behavior. With fewer than two observations R² is undefined. Multioutput aggregation must be specified (uniform average, variance weighted or raw values). Report MAE alongside R², especially if evaluation populations have different target variance.
Constant target policy
import warningsfrom sklearn.metrics import r2_scorewith warnings.catch_warnings(): warnings.simplefilter("ignore",RuntimeWarning) for p in [[4,4],[4,5]]: print(r2_score([4,4],p),r2_score([4,4],p,force_finite=False))Observed local output:
1.0 nan0.0 -infThe raw formula is undefined; the finite defaults are conventions, not evidence of predictive quality.
Common mistakes
Do not clip negative scores to zero, silently treat undefined cases as actual zero, or equate R² with percentage accuracy. Do not select on test data.
Practice and next steps
For truth [1,3], calculate SST and R² for predictions [2,2] and [0,4]. Explain why a constant-target policy matters. Complete the knowledge check and staged exercise. Next: Confusion matrix metrics.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
R squared and constant target — knowledge check
Apply r squared and constant target to new scenarios.
What does negative R² mean for a nonconstant target?
Why report constant-target policy?
Is evaluation mean a deployable predictor?
Can predictions have perfect correlation and poor R²?
Which score retains original units?