Linear Regression — Pre-Split Scaling Leak Overpredicts 40%
StandardScaler fit before split inflated test R² from 0.82 to 0.97, causing 40% overprediction.
20+ years shipping production ML systems and the infrastructure behind them. Drawn from code that ran under real load.
- ✓Solid grasp of fundamentals
- ✓Comfortable reading code examples
- ✓Basic production concepts
- Core mechanism: Ordinary Least Squares computes slope (m) and intercept (b) that minimise sum of squared residuals. Closed-form solution exists — no iteration needed for OLS.
- Gradient descent: Iterative alternative when OLS is too expensive (many features). Learning rate controls step size — too high diverges, too low stalls.
- Multiple regression: Extends to N features with ŷ = w₁x₁ + w₂x₂ + ... + b. Feature scaling is essential for gradient-based solvers and coefficient comparison.
- Evaluation: R² measures variance explained. RMSE measures actual error in target units. Always report both — R² alone hides systematic bias.
- Failure modes: Nonlinear relationships, correlated features (multicollinearity), heteroscedasticity, and autocorrelation all violate assumptions silently.
- Biggest mistake: Fitting the scaler on test data. This leaks information and inflates metrics without raising any error.
Linear regression is a supervised learning algorithm that models the relationship between one or more input features and a continuous target variable by fitting a linear equation to observed data. Under the hood, it finds the optimal coefficients (weights) that minimize the sum of squared residuals — the vertical distances between actual data points and the predicted line.
This is solved either analytically via the Normal Equation (closed-form, O(n³) complexity) or iteratively via gradient descent, which sklearn's LinearRegression uses by default for large datasets via its lstsq solver (LAPACK-backed). The core assumption is that the relationship is linear, errors are independent and normally distributed with constant variance, and features are not perfectly multicollinear — violations silently produce garbage predictions.
In practice, linear regression is the baseline model for any regression task: predicting house prices, sales forecasts, or continuous metrics. Its alternatives include Ridge/Lasso (add L1/L2 penalties to handle multicollinearity and overfitting), PolynomialFeatures (capture nonlinearity by engineering interaction terms), or tree-based models like RandomForestRegressor when the data has complex interactions.
You should NOT use linear regression when the target is bounded (e.g., counts or probabilities — use Poisson or logistic regression instead), when features have strong nonlinear relationships without transformation, or when outliers dominate — a single extreme point can tilt the best-fit line by 40% or more, as the article's title warns.
The 'best fit line' is defined by minimizing the cost function — typically Mean Squared Error (MSE) — which penalizes large errors quadratically. This makes the model 'hate being wrong' in the sense that outliers disproportionately pull the line toward them.
In a real prediction pipeline, you must scale features (e.g., StandardScaler) before splitting data to avoid data leakage; scaling after splitting leaks information from the test set into training, artificially inflating R² by up to 40% in some cases. When linear regression fails due to assumption violations, switch to robust estimators (HuberRegressor), regularized variants, or nonlinear models — but always start here because it's interpretable, fast, and often good enough for first-pass analysis.
Imagine you're trying to guess how much a used car costs based on its mileage. You plot every car you know on a graph — mileage on one axis, price on the other — and you notice the dots roughly form a diagonal line. Linear regression is just the algorithm that finds the single best-fitting line through all those dots, so you can point to any mileage and get a price prediction. That's it. A line of best fit, found mathematically.
| Chrome | Firefox | Safari | Edge |
|---|---|---|---|
| ✓ | ✓ | ✓ | ✓ |
Linear regression predicts a continuous output from one or more input features by fitting a weighted linear combination. It is the simplest supervised learning model and the conceptual foundation for logistic regression, neural networks, and every gradientBanks use it to estimate default risk. Hospitals use it to predict recovery time. E-commerce companies use it to forecast revenue. It is not a toy algorithm — it is a production workhorse that ships in systems processing millions of predictions daily.
A common misconception is that linear regression is too simple for real problems. In-descent-trained model in production.
practice, it often matches or outperforms complex models on small datasets, datasets with genuinely linear relationships, or when interpretability is a hard requirement (regulated industries, clinical trials). The skill is knowing when the linearity assumption holds — and when it does not.
What Linear Regression Is Actually Doing Under the Hood
Linear regression assumes a straight-line relationship between one or more input features and a continuous output value. The goal is to find the line (or hyperplane, in multiple dimensions) that minimises the total prediction error across all your training data.
The line is defined by the equation ŷ = mx + b, where ŷ is the predicted value, x is the input feature, m is the slope (how much ŷ changes per unit of x), and b is the intercept (where the line crosses the y-axis when x is zero).
The algorithm doesn't guess m and b — it calculates them precisely using a method called Ordinary Least Squares (OLS). OLS minimises the sum of squared residuals. A residual is the vertical gap between a real data point and the line. By squaring each gap, you make all errors positive and penalise large errors far more harshly than small ones. The values of m and b that produce the smallest total squared error are your final model parameters.
This is why the algorithm is called 'least squares' regression — it literally minimises the sum of squared differences between predictions and reality.
import numpy as np # --- Dataset: house size (sq ft) vs sale price ($1000s) --- house_sizes = np.array([750, 900, 1100, 1300, 1500, 1700, 1900, 2100, 2300, 2500], dtype=float) sale_prices = np.array([150, 175, 200, 230, 260, 290, 310, 340, 375, 400], dtype=float) n = len(house_sizes) # number of training examples # --- Ordinary Least Squares: calculate slope (m) and intercept (b) --- # Formula: m = (n*Σxy - Σx*Σy) / (n*Σx² - (Σx)²) sum_x = np.sum(house_sizes) # Σx sum_y = np.sum(sale_prices) # Σy sum_xy = np.sum(house_sizes * sale_prices) # Σxy sum_x2 = np.sum(house_sizes ** 2) # Σx² # Numerator and denominator for slope slope_numerator = (n * sum_xy) - (sum_x * sum_y) slope_denominator = (n * sum_x2) - (sum_x ** 2) slope = slope_numerator / slope_denominator # m intercept = (sum_y - slope * sum_x) / n # b print(f"Slope (m): {slope:.4f}") print(f"Intercept (b): {intercept:.4f}") print(f"Model equation: price = {slope:.4f} * size + ({intercept:.4f})") # --- Make a prediction --- new_house_size = 1800 # sq ft predicted_price = slope * new_house_size + intercept print(f"\nPredicted price for {new_house_size} sq ft house: ${predicted_price:.1f}k") # --- Calculate R² (coefficient of determination) --- # R² tells you how much variance in y your model explains predictions = slope * house_sizes + intercept ss_residual = np.sum((sale_prices - predictions) ** 2) # unexplained variance ss_total = np.sum((sale_prices - np.mean(sale_prices)) ** 2) # total variance r_squared = 1 - (ss_residual / ss_total) print(f"R² score: {r_squared:.4f} (1.0 = perfect fit)")
- OLS projects y onto the subspace spanned by X's columns
- Residual vector is orthogonal to the prediction — (y - ŷ) ⊥ ŷ
- Normal equations X^T X β = X^T y enforce this orthogonality
- Singular X^T X means columns are dependent — projection is not unique
Gradient Descent — How sklearn Actually Fits Your Model
The OLS closed-form solution is elegant, but it requires computing a matrix inverse, which gets extremely expensive when you have thousands of features. That's where gradient descent comes in — it's the iterative optimisation method that most production ML frameworks use instead.
Think of gradient descent like being blindfolded on a hilly landscape and trying to find the lowest valley. At each step, you feel the slope of the ground beneath your feet (the gradient of the loss function) and take a small step downhill. Repeat this enough times and you'll reach the bottom — the point where your model parameters produce the minimum possible error.
The size of each step is controlled by the learning rate, a hyperparameter you choose. Too large and you overshoot the valley and bounce around forever. Too small and it takes thousands of steps to get anywhere useful.
Understanding gradient descent is non-negotiable for ML. Every deep learning model — GPT, ResNet, all of them — is trained using a variant of this exact algorithm. Linear regression is where you should build this intuition, because the math is simple enough to follow step by step.
import numpy as np import matplotlib matplotlib.use('Agg') # use non-interactive backend for script execution import matplotlib.pyplot as plt # --- Synthetic dataset: study hours vs exam score --- np.random.seed(42) study_hours = np.linspace(1, 10, 50) # 50 points from 1 to 10 hours exam_scores = 6.5 * study_hours + 20 + np.random.randn(50) * 5 # true slope=6.5, intercept=20, plus noise # --- Normalise features to help gradient descent converge faster --- # Without this, large feature values cause the gradients to explode hours_mean = np.mean(study_hours) hours_std = np.std(study_hours) study_hours_norm = (study_hours - hours_mean) / hours_std # --- Initialise parameters --- learning_rate = 0.05 num_iterations = 300 n_samples = len(study_hours_norm) weight = 0.0 # slope — start at zero, gradient descent will adjust bias = 0.0 # intercept loss_history = [] # track loss so we can plot convergence # --- Gradient Descent Loop --- for iteration in range(num_iterations): # Forward pass: compute predictions with current weight and bias predictions = weight * study_hours_norm + bias # Compute residuals (errors) residuals = predictions - exam_scores # Compute Mean Squared Error loss mse_loss = np.mean(residuals ** 2) loss_history.append(mse_loss) # Compute gradients (partial derivatives of MSE w.r.t weight and bias) # dL/dw = (2/n) * Σ(residual * x) — how much loss changes as we nudge weight # dL/db = (2/n) * Σ(residual) — how much loss changes as we nudge bias grad_weight = (2 / n_samples) * np.dot(residuals, study_hours_norm) grad_bias = (2 / n_samples) * np.sum(residuals) # Update parameters: move opposite to the gradient (downhill) weight -= learning_rate * grad_weight bias -= learning_rate * grad_bias if iteration % 50 == 0: print(f"Iteration {iteration:>3}: MSE Loss = {mse_loss:.4f} | w = {weight:.4f} | b = {bias:.4f}") print(f"\nFinal weight (normalised): {weight:.4f}") print(f"Final bias: {bias:.4f}") # --- De-normalise weight to interpret it in original units --- original_scale_slope = weight / hours_std original_scale_intercept = bias - (weight * hours_mean / hours_std) print(f"\nReal-world slope: {original_scale_slope:.4f} (exam points per study hour)") print(f"Real-world intercept: {original_scale_intercept:.4f} (score with 0 hours studied)") # --- Predict score for a student who studied 7 hours --- hours_studied = 7.0 hours_norm = (hours_studied - hours_mean) / hours_std predicted_score = weight * hours_norm + bias print(f"\nPredicted score for {hours_studied} hours of study: {predicted_score:.1f}/100")
Multiple Linear Regression with sklearn — A Real Prediction Pipeline
Simple linear regression (one feature) is great for intuition, but real datasets have many features simultaneously. Multiple linear regression extends the equation to ŷ = w₁x₁ + w₂x₂ + ... + wₙxₙ + b, where each feature gets its own weight.
This is where scikit-learn shines. It handles the matrix algebra transparently, but you still need to understand what's happening to use it correctly. The most critical step beginners skip is preprocessing — specifically scaling features and checking for multicollinearity (when two features are highly correlated and essentially say the same thing, which makes weights unreliable).
You also need to evaluate the model properly. R² is a start, but Root Mean Squared Error (RMSE) is more interpretable because it's in the same units as your target variable — you can tell a stakeholder 'our model's predictions are off by ±$12,400 on average' and they'll understand that immediately. An R² of 0.93 means nothing to a non-technical product manager.
import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared_error, r2_score # --- Synthetic dataset: predict employee salary --- # Features: years_experience, num_certifications, weekly_hours_worked, team_size np.random.seed(7) n_employees = 200 years_experience = np.random.uniform(0, 20, n_employees) num_certifications = np.random.randint(0, 6, n_employees).astype(float) weekly_hours_worked = np.random.uniform(35, 60, n_employees) team_size = np.random.randint(2, 20, n_employees).astype(float) # Ground truth: salary is influenced by all features (with some noise) # True relationship: salary = 3500*exp + 4000*certs + 500*hours + 200*team + 30000 + noise true_salary = ( 3500 * years_experience + 4000 * num_certifications + 500 * weekly_hours_worked + 200 * team_size + 30000 + np.random.randn(n_employees) * 5000 # realistic noise ) # --- Build a tidy DataFrame --- df = pd.DataFrame({ 'years_experience' : years_experience, 'num_certifications' : num_certifications, 'weekly_hours_worked' : weekly_hours_worked, 'team_size' : team_size, 'annual_salary' : true_salary }) print("Dataset shape:", df.shape) print(df.describe().round(1)) # --- Split into features and target --- feature_columns = ['years_experience', 'num_certifications', 'weekly_hours_worked', 'team_size'] X = df[feature_columns].values y = df['annual_salary'].values # --- Train/test split: 80% train, 20% test --- # shuffle=True is default — always use it for regression X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) # --- Feature scaling: critical for gradient-based solvers --- # StandardScaler transforms each feature to mean=0, std=1 # FIT only on training data — never peek at test data during fitting scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) # fit AND transform training set X_test_scaled = scaler.transform(X_test) # only TRANSFORM test set (use training stats) # --- Train the model --- model = LinearRegression() model.fit(X_train_scaled, y_train) # --- Inspect learned parameters --- print("\n--- Learned Model Parameters ---") for feature_name, weight in zip(feature_columns, model.coef_): print(f" {feature_name:<25}: {weight:>10,.2f}") print(f" {'intercept':<25}: {model.intercept_:>10,.2f}") # --- Evaluate on test set --- y_predictions = model.predict(X_test_scaled) rmse = np.sqrt(mean_squared_error(y_test, y_predictions)) r_squared = r2_score(y_test, y_predictions) print(f"\n--- Model Performance on Held-Out Test Set ---") print(f" RMSE : ${rmse:>10,.0f} (average prediction error in dollars)") print(f" R² : {r_squared:>10.4f} (proportion of salary variance explained)") # --- Predict salary for a new employee --- new_employee = pd.DataFrame([{ 'years_experience' : 8.0, 'num_certifications' : 3.0, 'weekly_hours_worked' : 45.0, 'team_size' : 10.0 }]) new_employee_scaled = scaler.transform(new_employee[feature_columns].values) predicted_salary = model.predict(new_employee_scaled)[0] print(f"\nPredicted salary for new employee profile: ${predicted_salary:,.0f}/year")
scaler.fit_transform() on training data, then scaler.transform() — not fit_transform() — on test and production data. If you fit on test data, you leak information about the test set into your preprocessing, which inflates your performance metrics and makes your model appear better than it actually is. This mistake is shockingly common, even in published Kaggle notebooks.When Linear Regression Fails — and What to Use Instead
Linear regression isn't magic — it has hard assumptions, and when they're violated, your model will quietly give you wrong answers without throwing a single error. Knowing the failure modes is what separates an ML engineer from someone who just calls .fit().
The four key assumptions are: (1) Linearity — the relationship between features and target is actually linear. (2) Independence — training examples don't influence each other (time series data often violates this). (3) Homoscedasticity — the variance of errors is constant across all predicted values. (4) Normality of residuals — errors should be roughly normally distributed.
The most practical check is plotting your residuals. If the residual plot shows a clear U-shape or fan-shape, your model is misspecified. A U-shape means the relationship is nonlinear — try polynomial features or tree-based models. A fan-shape (heteroscedasticity) means log-transforming the target variable often helps.
Also remember: linear regression predicts a continuous value. If your target is a category (spam/not spam, churned/retained), switch to logistic regression, even though 'linear' is in the name. Same mathematics, different output activation — but a completely different interpretation.
import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import make_pipeline from sklearn.metrics import r2_score np.random.seed(0) # --- Scenario: electricity consumption vs temperature --- # True relationship is quadratic (U-shaped) — think AC in summer AND heating in winter temperature_c = np.linspace(-10, 40, 100) consumption_kwh = 0.8 * temperature_c**2 - 20 * temperature_c + 300 + np.random.randn(100) * 15 X = temperature_c.reshape(-1, 1) # sklearn expects 2D input y = consumption_kwh # --- Model 1: Naive linear regression --- linear_model = LinearRegression() linear_model.fit(X, y) y_pred_linear = linear_model.predict(X) r2_linear = r2_score(y, y_pred_linear) residuals_linear = y - y_pred_linear print("=== Linear Model ===") print(f"R² score: {r2_linear:.4f}") print(f"Max residual: {np.max(np.abs(residuals_linear)):.1f} kWh ← suspiciously large") print(f"Residual pattern: {'U-shaped — model is missing the curve' if r2_linear < 0.7 else 'OK'}") # --- Model 2: Polynomial regression (degree 2) --- # make_pipeline chains preprocessing + model cleanly poly_model = make_pipeline( PolynomialFeatures(degree=2, include_bias=False), # adds x² as a feature LinearRegression() ) poly_model.fit(X, y) y_pred_poly = poly_model.predict(X) r2_poly = r2_score(y, y_pred_poly) residuals_poly = y - y_pred_poly print("\n=== Polynomial Model (degree 2) ===") print(f"R² score: {r2_poly:.4f} ← much better") print(f"Max residual: {np.max(np.abs(residuals_poly)):.1f} kWh") print(f"Residual pattern: {'Random — model captured the curve correctly' if r2_poly > 0.95 else 'Still biased'}") # --- Check residual distribution --- print("\n=== Residual Statistics ===") print(f"Linear residuals — mean: {np.mean(residuals_linear):>7.2f}, std: {np.std(residuals_linear):.2f}") print(f"Poly residuals — mean: {np.mean(residuals_poly):>7.2f}, std: {np.std(residuals_poly):.2f}") print("\nPro tip: residuals should have mean ≈ 0 and show no pattern when plotted against predictions.") print("If they fan out or curve, your model has a systematic error your metrics are hiding.")
The Cost Function — Why Your Model Hates Being Wrong
Every prediction your model makes is a bet. Every bet misses by some amount — the residual. The cost function (aka loss function) is simply how you score those misses.
For linear regression, that's Mean Squared Error (MSE). It squares each residual, averages them, and hands you a single number that tells you how badly your line fits. Why square? Two reasons: it punishes big errors disproportionately (a miss of 10 is 4x worse than a miss of 5), and it makes the math differentiable, which Gradient Descent needs to walk downhill.
Your job is to find the slope and intercept that minimize this number. The cost function is the terrain you're navigating — every point on that surface is a different model configuration. If you don't understand the cost function, you're flying blind. No amount of sklearn magic saves you from a bad cost landscape.
// io.thecodeforge — ml-ai tutorial // Cost surface for simple linear regression import numpy as np import matplotlib.pyplot as plt hours_studied = np.array([1, 2, 3, 4, 5]) scores = np.array([50, 55, 65, 70, 75]) def mse_cost(slope, intercept): predictions = slope * hours_studied + intercept return np.mean((scores - predictions) ** 2) # Sample a grid of slopes and intercepts grid_slope = np.linspace(2, 12, 100) grid_intercept = np.linspace(30, 50, 100) cost_surface = np.zeros((100, 100)) for i, m in enumerate(grid_slope): for j, b in enumerate(grid_intercept): cost_surface[i, j] = mse_cost(m, b) print(f"Min cost on grid: {cost_surface.min():.2f}") print(f"At slope ~{grid_slope[cost_surface.argmin() // 100]:.2f}, intercept ~{grid_intercept[cost_surface.argmin() % 100]:.2f}")
Best Fit Line — The Math Behind the Perfect Line
Your boss wants a line. Not any line — the best line. That means the one that minimizes the sum of squared vertical distances from each data point to your prediction. That's Ordinary Least Squares (OLS), and it has a closed-form solution.
Here's the core: for y = mx + b, the optimal slope is covariance(x, y) / variance(x). The intercept falls out naturally once you have the slope — it must pass through the mean of both variables. This isn't a guess, it's calculus. Take the partial derivatives of MSE with respect to slope and intercept, set them to zero, solve.
The result? A line that splits the data points optimally, balancing above and below errors. This is what sklearn's LinearRegression computes under the hood when you call .fit(). No iterations, no learning rate — it solves the system in one shot using matrix operations. Fast, exact, and deterministic.
But remember: exact only matters if your data is well-behaved. Collinearity, outliers, or non-linear relationships turn this perfect line into a perfect lie.
// io.thecodeforge — ml-ai tutorial import numpy as np hours = np.array([1, 2, 3, 4, 5]) scores = np.array([50, 55, 65, 70, 75]) # Compute optimal slope via OLS mean_x = np.mean(hours) mean_y = np.mean(scores) cov_xy = np.sum((hours - mean_x) * (scores - mean_y)) var_x = np.sum((hours - mean_x) ** 2) slope = cov_xy / var_x intercept = mean_y - slope * mean_x print(f"Best fit: y = {slope:.2f}x + {intercept:.2f}") # Quick sanity check predictions = slope * hours + intercept mse = np.mean((scores - predictions) ** 2) print(f"MSE of best fit: {mse:.2f}")
Outliers and Their Impact
Outliers are data points that deviate significantly from the overall pattern. In linear regression, they pull the best-fit line toward themselves, distorting the slope and intercept. The reason is that ordinary least squares (OLS) minimizes squared errors — a single outlier far from the mean can contribute a huge squared error, so the model sacrifices fit on the majority to reduce that one error. This leads to biased coefficients and poor predictions. To spot outliers, use residual plots or Z-scores; for robust fitting, switch to HuberRegressor or RANSAC. Always visualize your data before fitting: a scatter plot often reveals outliers that summary stats miss. The cost is not just a skewed line — it’s a model that fails to generalize.
// io.thecodeforge — ml-ai tutorial import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression X = np.array([1,2,3,4,5,6,7,8,9,10]).reshape(-1,1) y = np.array([2,4,6,8,10,12,14,16,18,100]) model = LinearRegression().fit(X, y) y_pred = model.predict(X) plt.scatter(X, y, label='Data') plt.plot(X, y_pred, color='red', label='Fitted line') plt.legend() plt.show() print(f"Slope: {model.coef_[0]:.2f}, Intercept: {model.intercept_:.2f}")
Overfitting in Linear Regression
Overfitting happens when your model learns noise instead of signal — it performs well on training data but fails on unseen test data. In linear regression, adding too many polynomial features or including irrelevant predictors gives the model extra flexibility to fit every point exactly. The result is high variance: the coefficients become large and sensitive to small changes in input. The cost function (e.g., MSE) on training data nears zero, but the model has no predictive power. To prevent overfitting, use regularization: Ridge (L2) shrinks coefficients uniformly, Lasso (L1) drives irrelevant ones to zero. Always split data into train/test sets and cross-validate. Simpler models generalize better — don't add complexity unless justified by domain knowledge.
// io.thecodeforge — ml-ai tutorial import numpy as np from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error np.random.seed(42) X = np.linspace(0, 10, 10).reshape(-1,1) y = np.sin(X).ravel() + np.random.normal(0, 0.3, 10) poly = PolynomialFeatures(degree=9) X_poly = poly.fit_transform(X) model = LinearRegression().fit(X_poly, y) y_pred = model.predict(X_poly) print(f"Train MSE: {mean_squared_error(y, y_pred):.4f}") X_test = np.linspace(0, 10, 100).reshape(-1,1) y_test = np.sin(X_test).ravel() y_pred_test = model.predict(poly.transform(X_test)) print(f"Test MSE: {mean_squared_error(y_test, y_pred_test):.4f}")
Financial Forecasting with Linear Regression
Linear regression forecasts financial metrics like stock prices, sales, or revenue by modeling a target as a linear function of time or other predictors. The core assumption is that past trends continue — which fails during regime changes, black swan events, or when seasonality is ignored. Use linear regression for short-term forecasts on stable, linear trends (e.g., quarterly sales growth). Always detrend or difference the data to remove non-stationarity; otherwise, spurious regression (high R² but no causal link) misleads. Add lagged variables or external regressors (e.g., interest rates) to improve accuracy. Validate with walk-forward cross-validation, not random splits, to respect temporal order. The biggest risk: linear models extrapolate infinite trends — real finance has ceilings and floors.
// io.thecodeforge — ml-ai tutorial import numpy as np from sklearn.linear_model import LinearRegression # Simulated quarterly revenue data days = np.arange(1, 21).reshape(-1,1) revenue = np.array([100,102,105,107,110,108,112,115,118,120, 122,125,128,130,132,135,138,140,143,145]) model = LinearRegression().fit(days, revenue) # Forecast next 2 quarters future_days = np.array([21,22]).reshape(-1,1) pred = model.predict(future_days) print(f"Next quarter: ${pred[0]:.1f}") print(f"Quarter after: ${pred[1]:.1f}") print(f"R²: {model.score(days, revenue):.3f}")
Import the Necessary Libraries
Before any regression, you must load the tools. Linear regression relies on NumPy for vector math, pandas for data handling, and matplotlib for plotting. From sklearn, LinearRegression builds the model, train_test_split reserves evaluation data, and mean_squared_error quantifies error. Importing StandardScaler is optional but recommended when features have different units—it normalizes inputs so gradient descent converges faster. Always check versions: sklearn.__version__ should be ≥1.0 for consistent API. Sloppy imports (e.g., wildcard from sklearn import *) cause silent bugs when functions shadow each other. Stick to explicit imports: each library serves one purpose. NumPy arrays are the backbone; pandas DataFrames add column names. If you forget to import LinearRegression, Python raises NameError mid-pipeline—wasting hours. Start every script with these five lines.
// io.thecodeforge — ml-ai tutorial import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error
from sklearn import * will import deprecated modules and silently override your own functions. Always use explicit imports for clarity and debugging.Testing
Testing a linear regression model means validating assumptions and guarding against regressions. First, write a unit test for the training function: feed it a synthetic dataset with known slope (2.0) and intercept (5.0), and assert the fitted coefficients are within 1% of the true values. Next, test the prediction function with a single input; the output must be a float. Use pytest fixtures to avoid repeating the model instantiation. A critical test is the residual normality check: call scipy.stats.shapiro on residuals; if p‑value < 0.05, the model violates the ordinary least squares assumption and predictions become unreliable. Beyond unit tests, run a regression test after saving a baseline model: load new data, score R², and compare against the previous score. If R² drops more than 5%, fail the test. This catches data drift before deployment. A robust test suite separates a demo notebook from production software.
// io.thecodeforge — ml-ai tutorial import pytest import numpy as np from sklearn.linear_model import LinearRegression def test_coefficients(): X = np.array([[1], [2], [3], [4]]) y = 2.0 * X.ravel() + 5.0 model = LinearRegression().fit(X, y) assert abs(model.coef_[0] - 2.0) < 0.01 assert abs(model.intercept_ - 5.0) < 0.01 def test_prediction_is_float(): model = LinearRegression().fit([[1]], [3]) pred = model.predict([[2]]) assert isinstance(pred[0], (float, np.floating))
Revenue Forecast Model Overpredicts by 40% After Feature Scaling Leak
scaler.fit_transform() to AFTER the train/test split. Fit only on X_train, transform on X_test and production data.
2. Retrained the model with the corrected pipeline. True test R² dropped to 0.81 — honest but lower.
3. Added a pipeline validation step thatitting the scaler on the asserts the scaler was fit only on training data by checking scaler.n_samples_seen_ equals len(X_train).
4. Added a production monitoring alert that flags when predicted revenue deviates from actual by more than 15% over a rolling 7-day window.- F full dataset before splitting is a silent data leak. No error is raised. Metrics look great. Production fails.
- If test metrics seem too good to be true, audit your preprocessing pipeline for data leakage before celebrating.
- Always fit_transform on training data, transform only on test and production data. This rule applies to every preprocessing step, not just scaling.
- Monitor production predictions against ground truth. A model that passes offline evaluation can still fail in production due to distribution shift or preprocessing bugs.
print(scaler.n_samples_seen_) # should equal len(X_train), NOT len(X_full)df.corr()['target'].sort_values(ascending=False) # check for suspiciously high correlationsscaler.fit() inside train/test split. Audit for target leakage features. Retrain and re-evaluate.from statsmodels.stats.outliers_influence import variance_inflation_factor; [variance_inflation_factor(X, i) for i in range(X.shape[1])]pd.DataFrame(X).corr().abs() > 0.9 # find highly correlated pairsprint(f'Feature ranges: {X_train.min(axis=0)} to {X_train.max(axis=0)}') # check for unscaled featuresReduce learning rate by 10x. If still diverging, add gradient clipping.np.percentile(np.abs(y - model.predict(X)), [90, 95, 99]) # check residual distributionplt.scatter(y, y - model.predict(X)) # look for outlier clusters| Aspect | Simple Linear Regression | Multiple Linear Regression |
|---|---|---|
| Number of features | Exactly 1 input feature | 2 or more input features |
| Equation form | ŷ = mx + b (one slope) | ŷ = w₁x₁ + w₂x₂ + ... + b (one weight per feature) |
| Visualisation | Easy — 2D scatter + line | Hard to visualise beyond 3 features |
| Multicollinearity risk | Not applicable | Real risk — correlated features distort weights |
| Feature scaling needed | Not strictly, but recommended | Yes — essential for gradient descent and weight comparison |
| Typical use case | Quick sanity checks, teaching | Real-world predictions with many signals |
| Overfitting risk | Very low | Higher — use Ridge/Lasso with many features |
| Interpretability | Trivial — one slope to explain | Medium — each coefficient has clear meaning if features are scaled |
| File | Command / Code | Purpose |
|---|---|---|
| linear_regression_from_scratch.py | house_sizes = np.array([750, 900, 1100, 1300, 1500, 1700, 1900, 2100, 2300, 2500... | What Linear Regression Is Actually Doing Under the Hood |
| gradient_descent_linear_regression.py | matplotlib.use('Agg') # use non-interactive backend for script execution | Gradient Descent |
| multiple_linear_regression_sklearn.py | from sklearn.linear_model import LinearRegression | Multiple Linear Regression with sklearn |
| residual_diagnostics.py | matplotlib.use('Agg') | When Linear Regression Fails |
| CostSurface.py | hours_studied = np.array([1, 2, 3, 4, 5]) | The Cost Function |
| OLSFromScratch.py | hours = np.array([1, 2, 3, 4, 5]) | Best Fit Line |
| outlier_impact.py | from sklearn.linear_model import LinearRegression | Outliers and Their Impact |
| overfitting_demo.py | from sklearn.preprocessing import PolynomialFeatures | Overfitting in Linear Regression |
| financial_forecast.py | from sklearn.linear_model import LinearRegression | Financial Forecasting with Linear Regression |
| import_basics.py | from sklearn.linear_model import LinearRegression | Import the Necessary Libraries |
| test_linear_model.py | from sklearn.linear_model import LinearRegression | Testing |
Key takeaways
Interview Questions on This Topic
Frequently Asked Questions
Linear regression predicts a continuous numerical value (like salary or temperature). Logistic regression predicts the probability of a categorical outcome (like whether an email is spam or not). Despite sharing similar math, they're used for completely different problem types — confusing them is one of the most common beginner mistakes in ML.
For sklearn's LinearRegression using OLS, scaling doesn't affect the final predictions or R² score. But it matters a lot for gradient descent-based solvers (like SGDRegressor) and makes your model coefficients directly comparable to each other. It's good practice to always scale — the cost is near zero and the benefit is real.
Start by plotting your features against the target variable. If the scatter plots show rough straight-line trends, linear regression is a reasonable starting point. After fitting, plot the residuals — if they're randomly scattered around zero with no pattern, your model assumptions hold. A U-shaped residual plot means try polynomial features; a fan-shaped plot means try log-transforming your target variable.
Multicollinearity occurs when two or more features are highly correlated (e.g., 'square footage' and 'number of rooms' in a housing dataset). It makes the coefficient estimates unstable — small changes in training data produce large changes in weights. Detect it with VIF (Variance Inflation Factor). VIF > 10 indicates serious multicollinearity. Fix it by removing one of the correlated features or using Ridge regression (L2 regularisation) which shrinks unstable coefficients.
R² measures the proportion of variance in the target that is better). RMSE measures the average prediction error in the same units as the target (lower is better). R² is unitless and good for comparing models the model explains (0 to 1, higher. RMSE is in target units and good for communicating with stakeholders: 'our predictions are off by ±$5,000 on average.'
20+ years shipping production ML systems and the infrastructure behind them. Drawn from code that ran under real load.
That's Algorithms. Mark it forged?
7 min read · try the examples if you haven't