Regression
Core Concepts

Regression

A complete guide to Regression analysis in Machine Learning: Ordinary Least Squares (OLS), cost functions, linear vs polynomial models, residuals, and performance metrics (RMSE, R²).

Imagine you are running a lemonade stand on a sidewalk during the summer. On a mild 65°F (18°C) spring day, you sell 20 cups. On a pleasant 75°F (24°C) afternoon, you sell 45 cups. On an 85°F (29°C) day, you sell 70 cups. On a hot 95°F (35°C) summer day, sales reach 95 cups. You plot these points on a grid: Temperature along the horizontal axis, and Cups Sold along the vertical axis. Looking at the chart, a clear trend emerges: the dots rise together in a steady upward line. Now, tomorrow's forecast predicts a 100°F (38°C) heatwave. How many lemons and ice bags should you prepare? If you place a straight ruler through the middle of your points and extend it to 100°F, the ruler points to approximately 108 cups. You have just performed Regression. In machine learning, Regression is the mathematical approach of finding the best-fitting line or curve through data points to predict continuous numerical values.

Definition

Regression is a foundational supervised machine learning technique used to model the relationship between one or more predictor features ($X$) and a continuous numerical target variable ($y$), enabling accurate estimates on new, unseen data.

Why It Matters

Many critical questions in business and science involve continuous quantities: temperature, revenue, blood pressure, power usage, travel speed, and market demand. Unlike classification, which groups items into distinct categories (such as Yes or No), Regression predicts continuous numerical amounts: how much, how long, or how many. It powers financial forecasting, dynamic ticket pricing, medical dosage calculations, energy grid management, and supply chain inventory planning.

How It Works

Here is how regression works mathematically, from simple linear relationships to multi-variable models: 1. Simple Linear Regression: The relationship between one input and the output is modeled as a straight line: $$y = w x + b$$ • $x$: The independent input feature (such as outdoor temperature). • $y$: The continuous target value (such as cups of lemonade sold). • $w$ (Weight or Slope): How much $y$ changes for each one-unit increase in $x$. • $b$ (Bias or Intercept): The baseline value of $y$ when $x$ is zero. 2. Multiple Linear Regression: Real-world outcomes usually depend on several factors simultaneously. For example, a home's sale price ($y$) depends on square footage ($x_1$), number of bedrooms ($x_2$), and distance to city centers ($x_3$): $$\hat{y} = w_1 x_1 + w_2 x_2 + w_3 x_3 + b = \mathbf{w}^T \mathbf{x} + b$$ 3. The Cost Function (Mean Squared Error): To find the best line, the algorithm minimizes the distance between predicted values ($\hat{y}$) and actual observations ($y$). The difference for each point is called the Residual: $e_i = y_i - \hat{y}_i$. Squaring these residuals eliminates negative signs and penalizes larger errors more heavily, leading to Mean Squared Error (MSE): $$MSE = \frac{1}{n} \sum_{i=1}^n (y_i - \hat{y}_i)^2$$ 4. Finding the Optimal Fit: • Ordinary Least Squares (OLS): For standard linear problems, a direct closed-form formula calculates optimal weights: $\mathbf{w} = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{y}$. • Gradient Descent: For large datasets with many records, an iterative optimization algorithm adjusts weights step by step until MSE reaches its lowest point. 5. Evaluation Metrics: • MAE (Mean Absolute Error): The average absolute error, expressed in original target units. • RMSE (Root Mean Squared Error): The square root of MSE, penalizing large outliers. • R² (Coefficient of Determination): The fraction of variance in $y$ explained by the model (ranging from 0.0 to 1.0).

The Linear Regression Optimization Workflow

1. Feature Ingestion (X, y)
Collect input variables X and continuous ground-truth target values y
2. Initial Parameters
Initialize slope weights w and bias intercept b with starting values
3. Residual Calculation
Compute differences between predicted values and actual observation points
4. Cost Minimization
Adjust parameters using closed-form OLS or iterative gradient descent updates
5. Validation (R², RMSE)
Evaluate prediction accuracy and check residual distributions on holdout test data

Key Points

  • Regression predicts continuous real numbers, whereas classification predicts discrete categories.
  • Linear Regression finds the line or plane that minimizes the sum of squared residuals.
  • Ordinary Least Squares (OLS) provides an exact mathematical solution for linear models.
  • R² measures the percentage of variance explained by the model (for example, R² = 0.85 means 85% of variance is explained).
  • Polynomial regression captures curved relationships by introducing polynomial terms like $x^2$ and $x^3$.

Steps

  1. Verify Linear Relationships

    Review scatter plots to check whether features exhibit roughly linear trends, and check for multicollinearity among input variables.

  2. Scale and Transform Features

    Standardize numeric columns using StandardScaler. If the target variable is skewed (such as income or housing prices), consider a logarithmic transform to normalize the distribution.

  3. Partition Training and Testing Data

    Split your data into separate training and test sets (such as an 80/20 split) to evaluate how well the model generalizes to new data.

  4. Fit the Regression Model

    Train a standard Linear Regression model, or use regularized variants (Ridge for L2 regularization or Lasso for L1 feature selection) when features are correlated.

  5. Inspect Residual Plots

    Plot residuals against predicted values. Errors should appear evenly scattered around zero without distinct funnel or curved patterns.

Formula

Ordinary Least Squares (OLS) Normal Equations (Closed-Form):
\hat{\mathbf{w}} = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{y}

Regularized Objectives:
\text{Ridge (L2): } \min_\mathbf{w} \frac{1}{2N} \|\mathbf{y} - \mathbf{X}\mathbf{w}\|_2^2 + \lambda \|\mathbf{w}\|_2^2
\text{Lasso (L1): } \min_\mathbf{w} \frac{1}{2N} \|\mathbf{y} - \mathbf{X}\mathbf{w}\|_2^2 + \lambda \|\mathbf{w}\|_1

Examples

Home Price Estimation

Estimating the market value of an apartment based on usable area, bedroom count, building age, and neighborhood. The output is a continuous dollar prediction, such as $465,000.

Electricity Demand Forecasting

Predicting hourly power consumption across a city based on outdoor temperature, time of day, humidity, and whether it is a workday or holiday.

Real-World Examples

Dynamic Pricing in Ride-Sharing

Transportation networks use regression models to forecast passenger demand and driver supply in 5-minute intervals across city zones. When projected demand outpaces available drivers, regression models calculate dynamic pricing multipliers to balance the market.

Clinical Drug Concentration Modeling

Medical researchers use non-linear regression to estimate medication concentration in a patient's bloodstream over time, taking into account patient body weight, kidney function, and dosage to ensure safe and effective treatment.

Technical Examples

Linear & Polynomial Regression with Scikit-Learn in Pythonpython
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error, r2_score

# 1. Generate non-linear ground truth: y = 0.5 * x^2 + 2 * x + noise
np.random.seed(42)
X = np.sort(np.random.uniform(-3, 3, size=(100, 1)), axis=0)
y = (0.5 * X**2 + 2 * X + np.random.normal(0, 0.5, size=(100, 1))).ravel()

# 2. Fit Standard Linear Regression
linear_model = LinearRegression()
linear_model.fit(X, y)
y_pred_linear = linear_model.predict(X)

# 3. Fit Polynomial Regression (Degree 2)
poly = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly.fit_transform(X) # Generates [x, x^2]
poly_model = LinearRegression()
poly_model.fit(X_poly, y)
y_pred_poly = poly_model.predict(X_poly)

# 4. Compare Performance
print("Linear Model:")
print(f"  RMSE: {np.sqrt(mean_squared_error(y, y_pred_linear)):.3f} | R²: {r2_score(y, y_pred_linear):.3f}")

print("\nPolynomial Model (Degree 2):")
print(f"  RMSE: {np.sqrt(mean_squared_error(y, y_pred_poly)):.3f} | R²: {r2_score(y, y_pred_poly):.3f}")
print(f"  Learned Equation: y = {poly_model.coef_[1]:.2f}*x² + {poly_model.coef_[0]:.2f}*x + {poly_model.intercept_:.2f}")
This script contrasts standard linear regression against polynomial regression. When the underlying phenomenon is curved, a straight linear model performs poorly ($R^2 \approx 0.65$), while polynomial feature expansion captures the true quadratic relationship with high precision ($R^2 > 0.95$).

Linear Regression vs Polynomial Regression

AspectLinear RegressionPolynomial Regression
Functional ShapeStraight line or flat hyperplane ($y = w_1 x_1 + w_2 x_2 + b$)Curved manifold ($y = w_1 x + w_2 x^2 + \dots + b$)
Model ComplexityLower complexity with high bias, resistant to overfittingHigher flexibility, can overfit if polynomial degrees are too high
InterpretabilityVery high: each coefficient represents a direct rate of changeModerate: individual polynomial terms are harder to interpret separately
Training SpeedVery fast closed-form matrix solutionSlightly slower as additional power terms increase feature count
Extrapolation Outside RangeExtends existing linear trend steadilyCan produce extreme swings outside the observed data range

The Gauss-Markov Theorem and Unbiased Estimation

The Gauss-Markov Theorem provides the theoretical foundation for linear regression. It states that when standard statistical conditions hold, the Ordinary Least Squares (OLS) estimator is the **Best Linear Unbiased Estimator (BLUE)**. Key Conditions: 1. Linearity in parameters. 2. Zero conditional mean of errors: the average error given the inputs is zero. 3. Full rank: features are not exact duplicates of each other. 4. Constant error variance (homoscedasticity) and uncorrelated errors. Under these conditions, OLS achieves the lowest variance among all possible linear unbiased estimators. If error variance changes across predictions (heteroscedasticity), OLS remains unbiased, but estimates become less statistically efficient, often calling for robust standard errors.

The LINE Residual Diagnostic Framework

To verify that a linear regression model is reliable, analysts check the **LINE** diagnostic criteria using residual plots: 1. L: Linearity: • Residuals plotted against predicted values should show a random scatter around zero without curved or arched shapes. 2. I: Independence: • Residuals should not show sequential patterns over time. Autocorrelation tests like the Durbin-Watson statistic help confirm independence in time-series data. 3. N: Normality: • Quantile-Quantile (Q-Q) plots should show residual points falling close to a straight diagonal reference line. 4. E: Equal Variance (Homoscedasticity): • The spread of residuals should remain reasonably uniform across all levels of predicted values, rather than forming a widening funnel.

Advantages

  • Highly interpretable: coefficients directly show feature influence and direction.
  • Computationally efficient: trains quickly and evaluates predictions in microseconds.
  • Supported by clear statistical foundations, including confidence intervals and hypothesis tests.
  • Serves as an essential baseline benchmark for continuous numerical prediction tasks.

Limitations

  • Assumes linear relationships and can struggle with complex non-linear interactions without extra transformations.
  • Can be sensitive to extreme outliers that pull the least-squares line off balance.
  • Prone to unstable coefficients when predictor features are strongly correlated with each other.

Interview Questions

What are the four classical assumptions of Ordinary Least Squares (OLS) regression?

The four standard assumptions are: 1) Linearity: the relationship between features and target is linear in parameters; 2) Independence: error terms are independent without autocorrelation; 3) Homoscedasticity: error variance remains constant across all predicted values; and 4) Normality: error terms are approximately normally distributed around zero, which is important for hypothesis testing and confidence intervals.

What is Multicollinearity, why does it matter, and how do you detect it?

Multicollinearity occurs when two or more predictor features in a regression model are strongly correlated with one another. While it does not necessarily degrade overall prediction accuracy, it makes individual coefficient estimates unstable and difficult to interpret. It can be detected using the Variance Inflation Factor (VIF), where values above 5 or 10 indicate significant correlation that may benefit from feature selection or Ridge regularization.

Practice Questions

  1. Given the three data points (1, 2), (2, 3), and (3, 5), explain how you would calculate the slope and intercept using least squares formulas.
  2. Explain how you would use a residual scatter plot to determine whether a regression model satisfies homoscedasticity.