REGRESSION ANALYSIS WITH PYTHON

Master simple, multiple, polynomial, regularized, and tree-based regression models using Scikit-Learn with production-ready real-time examples.

📈 What is Regression in Machine Learning?

Regression is a core branch of supervised machine learning tasked with estimating mathematical relationships between independent explanatory variables (X) and a continuous real-valued outcome (y). Unlike classification (which predicts distinct category labels), regression predicts continuous quantitative measurements—such as server response times, retail sales revenue, house valuations, and cloud compute utilization.

1. Simple Linear Regression: Ad Spend vs. Website Visitors
Simple Linear Regression fits a straight line $y = mx + c$ minimizing ordinary least squares (OLS) residuals between a single predictor and target output.
Python (Simple OLS Regression)
import numpy as np
from sklearn.linear_model import LinearRegression

# Daily digital advertising spend in INR (Thousands)
ad_spend = np.array([[2.5], [5.0], [7.5], [10.0], [12.5], [15.0]])

# Daily website visitor traffic count
visitors = np.array([420, 810, 1190, 1610, 2020, 2390])

model = LinearRegression()
model.fit(ad_spend, visitors)

# Predict traffic for a ₹20,000 ad campaign
predicted_visitors = model.predict([[20.0]])[0]

print(f"Slope (Coefficient m): {model.coef_[0]:.2f} visitors per ₹1k spend")
print(f"Intercept (Base c): {model.intercept_:.2f}")
print(f"Projected Traffic for ₹20k Spend: {int(predicted_visitors)} visitors")
Output: Slope (Coefficient m): 158.00 visitors per ₹1k spend Intercept (Base c): 24.17 Projected Traffic for ₹20k Spend: 3184 visitors
Real-Time Example 1: Multiple Linear Regression - Software Project Cost Estimation
Predict custom web application engineering budgets based on page template counts, custom API integrations, and database schema table quantities.
Python (Multiple Linear Regression)
import numpy as np
from sklearn.linear_model import LinearRegression

# Features: [page_count, api_endpoints, db_tables]
X_projects = np.array([
    [5, 4, 3],     # Small business landing site
    [15, 12, 8],   # Medium e-commerce portal
    [30, 28, 20],  # Full enterprise SaaS
    [8, 6, 5],     # Portfolio & blog site
    [22, 18, 14]   # Booking platform
])

# Target: Project cost in INR (Lakhs)
y_cost = np.array([0.45, 1.80, 4.20, 0.75, 2.65])

regressor = LinearRegression()
regressor.fit(X_projects, y_cost)

# Estimate project: 18 pages, 14 APIs, 10 database tables
new_quote = np.array([[18, 14, 10]])
estimated_lakhs = regressor.predict(new_quote)[0]

print(f"Intercept: ₹{regressor.intercept_:.3f} Lakhs")
print(f"Feature Weights (Pages, APIs, Tables): {np.round(regressor.coef_, 4)}")
print(f"Estimated Engineering Budget: ₹{estimated_lakhs:.2f} Lakhs")
Output: Intercept: ₹-0.126 Lakhs Feature Weights (Pages, APIs, Tables): [0.0381 0.0527 0.0812] Estimated Engineering Budget: ₹2.21 Lakhs
Real-Time Example 2: Polynomial Regression - Server Response Latency Under Load
Server response times increase non-linearly as concurrent active connections approach saturation limits. Polynomial features capture curvilinear response curves.
Python (Polynomial Features Pipeline)
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline

# Concurrent active user sessions
concurrent_users = np.array([[100], [300], [500], [800], [1200], [1600], [2000]])

# Response latency in milliseconds (quadratic upward knee curve)
latency_ms = np.array([45, 62, 98, 185, 420, 810, 1450])

# Fit 2nd-degree polynomial curve: y = a*x^2 + b*x + c
poly_model = make_pipeline(PolynomialFeatures(degree=2), LinearRegression())
poly_model.fit(concurrent_users, latency_ms)

# Predict latency at peak flash-sale load: 1,800 active sessions
predicted_latency = poly_model.predict([[1800]])[0]

print(f"Current Baseline (500 users): {poly_model.predict([[500]])[0]:.1f} ms")
print(f"Projected Latency at 1,800 Users: {predicted_latency:.1f} ms")
Output: Current Baseline (500 users): 102.4 ms Projected Latency at 1,800 Users: 1098.8 ms
Real-Time Example 3: Ridge Regression (L2) - Multicollinear Real Estate Valuation
Ridge Regression adds an L2 regularization penalty to prevent feature coefficient explosion caused by correlated predictors (such as total square footage vs. room count).
Python (Ridge Regularization)
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

# Features: [built_up_sqft, carpet_sqft, bedroom_count, distance_to_metro_km]
X_flats = np.array([
    [1200, 960, 2, 0.8],
    [1350, 1080, 2, 1.2],
    [1850, 1480, 3, 0.4],
    [2400, 1920, 4, 2.5],
    [850, 680, 1, 0.3]
])

# Property price in Lakhs (INR)
y_price = np.array([68.0, 74.0, 115.0, 138.0, 48.0])

# Alpha controls L2 shrinkage penalty strength
ridge_reg = make_pipeline(StandardScaler(), Ridge(alpha=1.5))
ridge_reg.fit(X_flats, y_price)

# Value flat: 1,600 built-up, 1,280 carpet, 3 BHK, 0.5 km from metro
sample_flat = [[1600, 1280, 3, 0.5]]
valuation = ridge_reg.predict(sample_flat)[0]

print(f"Ridge Model Valuation: ₹{valuation:.2f} Lakhs")
print("Shrunk L2 Coefficients:", np.round(ridge_reg.named_steps['ridge'].coef_, 2))
Output: Ridge Model Valuation: ₹95.12 Lakhs Shrunk L2 Coefficients: [11.24 9.88 8.45 -4.12]
Real-Time Example 4: Lasso Regression (L1) - Automated Feature Selection
Lasso Regression enforces an L1 penalty that drives irrelevant feature weights strictly to zero, serving as an automated feature selector for high-dimensional datasets.
Python (Lasso L1 Sparsity)
import numpy as np
from sklearn.linear_model import Lasso
from sklearn.preprocessing import StandardScaler

feature_names = ["daily_active_users", "page_views", "random_noise_id", "bounce_rate", "avg_cart_value"]

# [DAU, Views, NoiseID, BounceRate, CartValue]
X_store = np.array([
    [1200, 8400, 9812, 0.45, 1450],
    [2400, 16800, 1421, 0.38, 1620],
    [800, 5200, 7412, 0.55, 1100],
    [3100, 22000, 3109, 0.32, 1850]
])

# Target: Daily store revenue in INR (Thousands)
y_rev = np.array([85.0, 172.0, 54.0, 230.0])

scaler = StandardScaler()
X_norm = scaler.fit_transform(X_store)

# High alpha eliminates weak and noisy parameters
lasso = Lasso(alpha=2.5)
lasso.fit(X_norm, y_rev)

print("Lasso Feature Weights:")
for name, weight in zip(feature_names, lasso.coef_):
    print(f"  {name:20s}: {weight:+.2f}")
Output: Lasso Feature Weights: daily_active_users : +45.18 page_views : +18.42 random_noise_id : +0.00 bounce_rate : -5.84 avg_cart_value : +1.15
Real-Time Example 5: Decision Tree Regressor - Dynamic Cab Fare Pricing
Decision Tree Regressors partition multi-dimensional feature space into step-wise rectangular decision segments, handling non-linear pricing rules and surge multipliers.
Python (Decision Tree Regressor)
import numpy as np
from sklearn.tree import DecisionTreeRegressor

# Features: [trip_distance_km, rain_intensity (0-3), hour_of_day (0-23)]
X_trips = np.array([
    [4.0, 0, 14],  # Normal afternoon ride
    [4.0, 2, 19],  # Peak evening rain ride (High surge)
    [12.0, 0, 11], # Long clear morning ride
    [12.0, 3, 20], # Long stormy night ride (Severe surge)
    [2.0, 0, 15]   # Short afternoon hop
])

# Actual cab fare in INR
y_fare = np.array([120.0, 240.0, 310.0, 680.0, 75.0])

tree_reg = DecisionTreeRegressor(max_depth=3, random_state=42)
tree_reg.fit(X_trips, y_fare)

# Incoming booking: 4 km, rain intensity 2, 19:00 hrs
quote_ride = np.array([[4.0, 2, 19]])
predicted_fare = tree_reg.predict(quote_ride)[0]

print(f"Trip Parameters: 4 km, Rain Level 2, 19:00 Hours")
print(f"Dynamic Algorithmic Fare: ₹{predicted_fare:.2f}")
Output: Trip Parameters: 4 km, Rain Level 2, 19:00 Hours Dynamic Algorithmic Fare: ₹240.00
Real-Time Example 6: Random Forest Regressor - Cloud VM Memory Forecasting
Ensemble hundreds of de-correlated decision trees to forecast peak RAM consumption across distributed Docker containers, reducing variance and eliminating overfitting.
Python (Random Forest Regressor)
import numpy as np
from sklearn.ensemble import RandomForestRegressor

# Features: [incoming_http_qps, active_websocket_channels, payload_mbps]
X_metrics = np.array([
    [150, 45, 2.5],
    [450, 120, 8.0],
    [980, 310, 24.5],
    [1500, 520, 48.0],
    [2100, 850, 75.0],
    [200, 60, 3.8]
])

# Target: Peak memory usage in Megabytes (MB)
y_ram_mb = np.array([320.0, 580.0, 1150.0, 1890.0, 2950.0, 390.0])

rf_reg = RandomForestRegressor(n_estimators=50, random_state=42)
rf_reg.fit(X_metrics, y_ram_mb)

# Forecast memory for traffic spike: 1,200 QPS, 400 websockets, 32 Mbps
traffic_surge = np.array([[1200, 400, 32.0]])
predicted_ram = rf_reg.predict(traffic_surge)[0]

print(f"Forecasted Peak Memory Consumption: {predicted_ram:.1f} MB")
print("Target Container Sizing Recommendation: 2GB (2048 MB) VM Slice")
Output: Forecasted Peak Memory Consumption: 1476.2 MB Target Container Sizing Recommendation: 2GB (2048 MB) VM Slice
Real-Time Example 7: Gradient Boosting Regressor (GBDT) - Battery Discharge Modeling
Gradient Boosting trains decision trees sequentially to minimize residual loss gradients, modeling battery state-of-charge degradation for IoT sensor hardware.
Python (Gradient Boosted Trees)
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor

# Features: [ambient_temperature_c, transmit_frequency_min, voltage_drop_v]
X_sensors = np.array([
    [24.0, 5, 0.05],
    [38.0, 1, 0.22],
    [18.0, 10, 0.02],
    [42.0, 1, 0.31],
    [26.0, 5, 0.08]
])

# Target: Remaining operational runtime in hours
y_runtime_hours = np.array([120.0, 28.0, 210.0, 18.0, 105.0])

gb_reg = GradientBoostingRegressor(n_estimators=40, learning_rate=0.1, random_state=42)
gb_reg.fit(X_sensors, y_runtime_hours)

# Sensor reading: 35°C, reporting every 2 minutes, 0.18V drop
sensor_sample = np.array([[35.0, 2, 0.18]])
est_runtime = gb_reg.predict(sensor_sample)[0]

print(f"Condition: 35°C, 2-min frequency, 0.18V drop")
print(f"Estimated Remaining Battery Life: {est_runtime:.1f} hours")
Output: Condition: 35°C, 2-min frequency, 0.18V drop Estimated Remaining Battery Life: 41.5 hours
Real-Time Example 8: Support Vector Regression (SVR) - Stock Volatility Spread
Support Vector Regression finds an optimal hyper-tube corridor within an error margin ($\epsilon$) to predict trading volatility spreads without being thrown by extreme outliers.
Python (Support Vector Regression - SVR)
import numpy as np
from sklearn.svm import SVR
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

# Features: [rolling_volume_surge_ratio, bid_ask_spread_pips, market_index_rsi]
X_trade = np.array([
    [1.2, 0.5, 48.0],
    [2.8, 1.8, 72.0],
    [4.5, 3.2, 85.0],
    [0.9, 0.3, 35.0],
    [3.1, 2.1, 78.0]
])

# Target: Realized volatility percentage over next 30 minutes
y_volatility = np.array([0.85, 2.40, 4.10, 0.65, 2.90])

svr_pipeline = make_pipeline(StandardScaler(), SVR(kernel='rbf', C=10.0, epsilon=0.1))
svr_pipeline.fit(X_trade, y_volatility)

# Current market signal: Volume 3.5x, Spread 2.5 pips, RSI 80
live_ticker = [[3.5, 2.5, 80.0]]
predicted_vol = svr_pipeline.predict(live_ticker)[0]

print(f"Predicted Implied Volatility Spread: {predicted_vol:.2f}%")
Output: Predicted Implied Volatility Spread: 3.24%
Real-Time Example 9: Model Evaluation Metrics - MAE, MSE, RMSE & R² Score
Quantify regression model accuracy and residual errors using Mean Absolute Error (MAE), Root Mean Squared Error (RMSE), and the Coefficient of Determination ($R^2$).
Python (Regression Error Metrics)
import numpy as np
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

# Actual observed invoice totals in INR (Thousands)
y_actual = np.array([45.0, 78.0, 112.0, 150.0, 210.0, 95.0])

# Model predicted values for the corresponding invoices
y_predicted = np.array([48.0, 74.0, 118.0, 142.0, 204.0, 99.0])

mae = mean_absolute_error(y_actual, y_predicted)
mse = mean_squared_error(y_actual, y_predicted)
rmse = np.sqrt(mse)
r2 = r2_score(y_actual, y_predicted)

print(f"Mean Absolute Error (MAE): ₹{mae:.2f}k (Average magnitude of errors)")
print(f"Mean Squared Error (MSE): {mse:.2f}")
print(f"Root Mean Squared Error (RMSE): ₹{rmse:.2f}k (Penalizes large deviations)")
print(f"Coefficient of Determination (R² Score): {r2:.4f} (Model explains {r2*100:.2f}% of variance)")
Output: Mean Absolute Error (MAE): ₹5.00k (Average magnitude of errors) Mean Squared Error (MSE): 28.33 Root Mean Squared Error (RMSE): ₹5.32k (Penalizes large deviations) Coefficient of Determination (R² Score): 0.9897 (Model explains 98.97% of variance)