python
sklearn
multiple linear regression
r-squared
data analysis

python sklearn multiple linear regression display r-squared

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

In scikit-learn, R-squared (R^2) is a standard metric for linear regression goodness-of-fit. For multiple linear regression, you typically fit LinearRegression on multiple feature columns and evaluate with model.score or r2_score. Correct train/test splitting is important to avoid overly optimistic values.

Core Sections

Fit multiple linear regression

python
1from sklearn.model_selection import train_test_split
2from sklearn.linear_model import LinearRegression
3from sklearn.metrics import r2_score
4
5X = df[["x1", "x2", "x3"]]
6y = df["target"]
7
8X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
9
10model = LinearRegression()
11model.fit(X_train, y_train)

Display R-squared

Two common options:

python
1r2_via_score = model.score(X_test, y_test)
2
3pred = model.predict(X_test)
4r2_via_metric = r2_score(y_test, pred)
5
6print(r2_via_score, r2_via_metric)

Values should match for regression model evaluation.

Show adjusted R-squared

Sklearn does not provide adjusted R² directly; compute manually.

python
1n = len(y_test)
2p = X_test.shape[1]
3adj_r2 = 1 - (1 - r2_via_score) * (n - 1) / (n - p - 1)
4print(adj_r2)

Useful when comparing models with different feature counts.

Interpret values carefully

High R² does not imply causal correctness or out-of-sample robustness. Residual diagnostics still matter.

Cross-validation for stable estimate

Use CV to estimate performance variability instead of one split.

Common Pitfalls

  • Reporting training-set R² as final model quality.
  • Comparing models by R² only without residual/error distribution checks.
  • Ignoring adjusted R² when adding many weak predictors.
  • Using leakage-prone features and inflating metric values.
  • Forgetting to handle non-linear relationships where linear model underfits.

Implementation Playbook

To make this technique dependable in production, treat implementation as a repeatable operating pattern rather than a one-time code change. Start by defining a baseline with known inputs, expected outputs, and measurable latency or resource behavior. Baselines are essential because many failures emerge after environment drift, dependency upgrades, or infrastructure changes that do not touch your business logic directly. With a baseline, you can quickly identify whether a regression came from code, configuration, or platform behavior.

Next, build a compact validation matrix that exercises three categories: normal behavior, edge cases, and explicit failure modes. Keep tests deterministic and cheap enough to run in local development and CI. If your flow depends on external services, include contract fixtures or mocks for fast checks and reserve a smaller set of integration tests for environment verification. Pair correctness checks with observability: log correlation identifiers, branch decisions, and output status in structured form so incidents can be diagnosed without guesswork.

Before rollout, define operational controls up front. Specify timeout values, retry policy, fallback behavior, and rollback triggers. Roll out incrementally instead of changing multiple risk dimensions at once. A staged rollout reduces blast radius and makes it easier to attribute behavior changes to one cause. Capture final operating assumptions in a short runbook: prerequisites, compatibility constraints, known warning signs, and first-response actions. This prevents repeated rediscovery and improves handoff quality across teams.

Use this execution checklist every time you modify this part of the system:

text
11. Record baseline inputs, outputs, and runtime metrics
22. Run deterministic happy-path and edge-case tests
33. Validate failure handling and fallback behavior
44. Verify dependency and environment compatibility
55. Roll out incrementally with explicit rollback criteria
66. Update runbook notes with observed outcomes

Final Deployment Note

Before rollout, execute one final smoke test in an environment that matches production topology as closely as possible. Validate not only functional output but also observability signals such as logs, metrics, and error counters so silent regressions are visible immediately. If behavior differs from baseline, revert quickly and compare dependency versions, environment variables, and infrastructure assumptions before retrying. A short, repeatable pre-release check usually saves far more incident time than it costs during delivery.

Summary

To display R-squared in sklearn multiple linear regression, use model.score or r2_score on held-out data. Include adjusted R² and validation strategy when model comparison requires stronger statistical grounding.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Practice ML system design

All Rights Reserved.