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
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
Verify Linear Relationships
Review scatter plots to check whether features exhibit roughly linear trends, and check for multicollinearity among input variables.
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.
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.
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.
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}\|_1Examples
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
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}")Linear Regression vs Polynomial Regression
| Aspect | Linear Regression | Polynomial Regression |
|---|---|---|
| Functional Shape | Straight 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 Complexity | Lower complexity with high bias, resistant to overfitting | Higher flexibility, can overfit if polynomial degrees are too high |
| Interpretability | Very high: each coefficient represents a direct rate of change | Moderate: individual polynomial terms are harder to interpret separately |
| Training Speed | Very fast closed-form matrix solution | Slightly slower as additional power terms increase feature count |
| Extrapolation Outside Range | Extends existing linear trend steadily | Can produce extreme swings outside the observed data range |
The Gauss-Markov Theorem and Unbiased Estimation
The LINE Residual Diagnostic Framework
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
- 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.
- Explain how you would use a residual scatter plot to determine whether a regression model satisfies homoscedasticity.
