How to Calculate R2 in Tensorflow
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
R-squared (R²) measures how well a regression model's predictions match the actual values. It ranges from negative infinity to 1, where 1 means perfect prediction, 0 means the model is no better than predicting the mean, and negative values mean the model is worse than predicting the mean. TensorFlow does not include R² as a built-in metric, but it can be implemented as a custom metric or computed using tf.keras.metrics.
R² Formula
R² = 1 - SS_res / SS_tot
Where:
- SS_res (residual sum of squares) = Σ(y_true - y_pred)²
- SS_tot (total sum of squares) = Σ(y_true - mean(y_true))²
Method 1: Custom Keras Metric Class
The most robust approach — works correctly with batched training:
A simpler approach that handles batching correctly:
Using the Custom Metric
Method 2: Post-Training Computation
Compute R² after training using NumPy or sklearn — simpler and guaranteed correct:
Method 3: TensorFlow-Only Computation
Method 4: Using tfa.metrics (TensorFlow Addons)
TensorFlow Addons includes an R² metric:
Note: TensorFlow Addons is in maintenance mode. For new projects, use the custom metric approach.
R² as a Custom Loss Function
You can also optimize R² directly as a loss (minimize 1 - R²):
Interpreting R² Values
| R² Value | Interpretation |
| 1.0 | Perfect prediction |
| 0.9 - 1.0 | Excellent fit |
| 0.7 - 0.9 | Good fit |
| 0.4 - 0.7 | Moderate fit |
| 0.0 - 0.4 | Poor fit |
| < 0 | Worse than predicting the mean |
Common Pitfalls
- Batch-wise R² is misleading: Computing R² per batch and averaging gives wrong results because the mean of y_true differs across batches. Always accumulate sums across all batches (as in the custom metric) or compute R² on the full dataset after training.
- R² on training data: R² on training data always improves with more model complexity (overfitting). Always evaluate on a held-out test set. Use adjusted R² if comparing models with different numbers of features.
- Multi-output regression: For models with multiple outputs, compute R² per output or use a weighted average. The custom metric above assumes a single output — reshape multi-output predictions accordingly.
- Negative R²: A negative R² does not mean the model is bad in absolute terms — it means it is worse than always predicting the mean. This often indicates a bug (wrong features, wrong target scaling) rather than a modeling issue.
- Scale sensitivity: R² is invariant to the scale of the target variable, unlike MSE or MAE. This makes it useful for comparing models across different datasets but can hide issues with prediction magnitude.
Summary
- Implement R² as a custom
tf.keras.metrics.Metricsubclass for use during training - Accumulate SS_res, sum(y), sum(y²), and count across batches for correct epoch-level R²
- Use
sklearn.metrics.r2_scorefor post-training evaluation — simpler and guaranteed correct - R² = 1 means perfect prediction; R² = 0 means no better than predicting the mean; R² < 0 means worse
- Always evaluate R² on test data, not training data
Related reading
- How to calculate the accuracy for multilabel classification with tf.metrics?
- How to calculate the flops of a tensorflow model loaded from pb file
- How to change a learning rate for Adam in TF2?
- How to change batch size dynamically in Tensorflow 2.0 Dataset?
- How to calculate TFIDF for a single new document to be classified?
- How to calculate the actual size of a .fit-trained model in sklearn?
- How to calculate the regularization parameter in linear regression
- How to change a dataframe column from String type to Double type in PySpark?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.