End-to-end linear regression: what drives car sales?
The full preprocessing and modelling chain from Classes 6, 9 and 10 in one leak-free script: audit, split, outlier capping, KNN imputation, encoding, VIF, OLS, evaluation and a clear final equation.
Best read after Statistics & Machine Learning 10: Linear Regression: Fitting, Interpreting, Assumptions and Diagnostics in the Data Science & AI handbook.
1. Why it matters
- Regression case studies are the most common take-home assignment for analyst and data-science roles.
- Each preprocessing step changes the answer; doing them in the wrong order leaks test information and overstates accuracy.
- Clients want drivers they can act on (price, efficiency, vehicle type), not only a score.
2. Key ideas
3. Step by step
- Audit: missing values, ranges and impossible values.
- Split 70:30 before any treatment.
- Cap outliers using train IQR fences; apply the same limits to test.
- Impute missing values with KNNImputer fitted on train.
- One-hot encode categories with drop_first; log-transform the skewed target.
- Remove multicollinearity with VIF, protecting business-critical variables.
- Fit OLS on train; keep significant drivers; refit.
- Evaluate RMSE, MAPE and R2 on train and test; write the final equation and driver effects.
4. Code you can run
Install once: pip install numpy pandas scipy scikit-learn statsmodels, then run python c5_car_sales_regression.py. The data is generated inside the script, so it runs anywhere.
"""End-to-end linear regression case study: what drives car sales?
Every preprocessing step from the classes in one script: data audit, train/test split,
outlier capping, missing-value imputation (SimpleImputer vs KNNImputer), encoding, VIF
feature selection, statsmodels OLS, evaluation and an over/underfitting check.
Rule used throughout: learn every preprocessing value (percentiles, medians, neighbours)
from the TRAINING set only, then apply it to the test set, so the test stays unseen.
Synthetic data shaped like the class's car-sales file. Run: python c5_car_sales_regression.py"""
import numpy as np
import pandas as pd
import statsmodels.api as sm
from sklearn.impute import KNNImputer, SimpleImputer
from sklearn.metrics import mean_absolute_percentage_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
from statsmodels.stats.outliers_influence import variance_inflation_factor
rng = np.random.default_rng(21)
n = 200
brands = ["Maruti", "Hyundai", "Tata", "Honda", "Toyota", "Kia", "Mahindra", "Skoda"]
df = pd.DataFrame({
"brand": rng.choice(brands, n),
"vehicle_type": rng.choice(["Hatchback", "Sedan", "SUV"], n, p=[.4, .3, .3]),
"engine_size": rng.normal(1.6, .45, n).clip(.8, 3.5).round(1),
})
df["horsepower"] = (55 * df.engine_size + rng.normal(10, 9, n)).round(0)
df["curb_weight"] = (750 + 280 * df.engine_size + np.where(df.vehicle_type == "SUV", 250, 0) + rng.normal(0, 60, n)).round(0)
df["length_mm"] = (3700 + 0.9 * (df.curb_weight - 750) + rng.normal(0, 90, n)).round(0)
df["fuel_capacity"] = (35 + 0.012 * df.curb_weight + rng.normal(0, 3, n)).round(1)
df["fuel_efficiency"] = (27 - 3.2 * df.engine_size + rng.normal(0, 1.4, n)).round(1)
df["price_lakh"] = (2.5 + 4.2 * df.engine_size + np.where(df.vehicle_type == "SUV", 3, 0) + rng.normal(0, 1.2, n)).round(2)
df["resale_value_lakh"] = (df.price_lakh * rng.uniform(.45, .85, n) + rng.normal(0, .8, n)).round(2)
log_sales = 4.2 - 0.12 * df.price_lakh + 0.06 * df.fuel_efficiency + np.where(df.vehicle_type == "SUV", .25, 0) + rng.normal(0, .18, n)
df["sales_thousands"] = np.exp(log_sales).round(2)
for col, k in [("resale_value_lakh", 35), ("fuel_efficiency", 8), ("curb_weight", 5)]:
df.loc[rng.choice(n, k, replace=False), col] = np.nan # missing values
bad = rng.choice(n, 4, replace=False)
df.loc[bad, "horsepower"] *= 10 # data-entry errors (extra zero)
df.loc[bad[:2], "price_lakh"] *= 10
# STEP 1 Data audit
print("STEP 1 Data audit")
num = [c for c in df.select_dtypes("number").columns if c != "sales_thousands"]
audit = pd.DataFrame({"missing": df[num].isna().sum(), "p1": df[num].quantile(.01), "median": df[num].median(),
"p99": df[num].quantile(.99), "max": df[num].max()}).round(2)
print(audit.to_string())
# STEP 2 Split BEFORE any treatment that learns from the data
train, test = train_test_split(df, test_size=0.3, random_state=1)
train, test = train.copy(), test.copy()
print(f"\nSTEP 2 Train/test split 70:30 -> train {len(train)} cars, test {len(test)} cars")
# STEP 3 Outlier capping with limits learned on train
hp = train.horsepower
q1, q3 = hp.quantile([.25, .75])
print(f"\nSTEP 3 Three outlier rules for horsepower (train): IQR fences [{q1 - 1.5 * (q3 - q1):.0f}, {q3 + 1.5 * (q3 - q1):.0f}] | "
f"mean +/- 3 SD [{hp.mean() - 3 * hp.std():.0f}, {hp.mean() + 3 * hp.std():.0f}] | percentiles [{hp.quantile(.01):.0f}, {hp.quantile(.99):.0f}]")
print(" the 99th percentile still sits inside the errors (more than 1% of rows are wrong), so cap with the IQR fences")
def iqr_fences(s):
a, b = s.quantile([.25, .75])
return a - 1.5 * (b - a), b + 1.5 * (b - a)
limits = {c: iqr_fences(train[c]) for c in num}
before = int((train.horsepower > limits["horsepower"][1]).sum())
for part in (train, test):
for c, (lo, hi) in limits.items():
part[c] = part[c].clip(lo, hi)
print(f" capped every numeric column at its train IQR fences: {before} horsepower values capped, max {df.horsepower.max():.0f} -> {train.horsepower.max():.0f}")
# STEP 4 Missing values: compare SimpleImputer (median) and KNNImputer, both fitted on train
mask = test.resale_value_lakh.isna()
expected = test.price_lakh[mask] * .65 # what resale should be on average
simple = SimpleImputer(strategy="median").fit(train[num])
knn = KNNImputer(n_neighbors=5).fit(train[num])
err_s = np.abs(pd.DataFrame(simple.transform(test[num]), columns=num, index=test.index).resale_value_lakh[mask] - expected).mean()
err_k = np.abs(pd.DataFrame(knn.transform(test[num]), columns=num, index=test.index).resale_value_lakh[mask] - expected).mean()
print(f"\nSTEP 4 {int(mask.sum())} missing resale values in test: average error SimpleImputer(median) {err_s:.2f} lakh | KNNImputer(k=5) {err_k:.2f} lakh -> using KNNImputer")
train[num] = knn.transform(train[num])
test[num] = knn.transform(test[num])
# STEP 5 Encoding: one-hot with drop_first (avoids the dummy-variable trap); log of the skewed target
train = pd.get_dummies(train, columns=["vehicle_type", "brand"], drop_first=True, dtype=float)
test = pd.get_dummies(test, columns=["vehicle_type", "brand"], drop_first=True, dtype=float).reindex(columns=train.columns, fill_value=0)
for part in (train, test):
part["ln_sales"] = np.log(part.sales_thousands)
print(f"\nSTEP 5 One-hot encoding -> {train.shape[1] - 2} features; target ln(sales): skew {train.sales_thousands.skew():.2f} -> {train.ln_sales.skew():.2f}")
# STEP 6 VIF: drop the worst variable until every VIF <= 5, but keep what the business must explain
features = [c for c in train.columns if c not in ("sales_thousands", "ln_sales")]
KEEP = {"price_lakh"} # the lever the client controls
print("\nSTEP 6 VIF elimination (multicollinearity), protecting", sorted(KEEP))
while True:
X = sm.add_constant(train[features])
vif = pd.Series([variance_inflation_factor(X.values, i) for i in range(1, X.shape[1])], index=features)
worst = vif.drop(list(KEEP)).idxmax()
if vif[worst] <= 5:
break
print(f" drop {worst:<18} VIF = {vif[worst]:5.1f}")
features.remove(worst)
print(f" kept {len(features)} features, max VIF {vif.max():.2f}")
def fit_and_score(feats, label):
model = sm.OLS(train.ln_sales, sm.add_constant(train[feats])).fit()
res = {}
for name, part in (("train", train), ("test", test)):
pred = np.exp(model.predict(sm.add_constant(part[feats], has_constant="add")))
res[name] = (np.sqrt(mean_squared_error(part.sales_thousands, pred)), mean_absolute_percentage_error(part.sales_thousands, pred),
r2_score(part.sales_thousands, pred))
print(f"\n{label}: {len(feats)} features, adjusted R2 on train {model.rsquared_adj:.3f}")
print(f" {'':6}{'RMSE':>8}{'MAPE':>8}{'R2':>8}")
for name in ("train", "test"):
print(f" {name:<6}{res[name][0]:8.2f}{res[name][1]:8.1%}{res[name][2]:8.3f}")
ratio = res["test"][0] / res["train"][0]
print(" verdict:", "overfitting (test error much higher than train)" if ratio > 1.3
else "underfitting (both errors high)" if res["train"][2] < .3 else "good fit: train and test errors are close")
return model
# STEP 7 Full model, then STEP 8 keep only significant drivers (p < 0.05) and refit
model = fit_and_score(features, "STEP 7 OLS with all VIF-screened features")
sig = model.pvalues.drop("const")
drivers = list(sig[sig < .05].index)
model = fit_and_score(drivers, "STEP 8 OLS with significant drivers only")
print("\n driver coef effect on sales per unit")
for f in drivers:
print(f" {f:<20}{model.params[f]:+.3f} about {np.expm1(model.params[f]) * 100:+.1f}%")
print(f" equation: ln(sales) = {model.params['const']:.2f} " + " ".join(f"{v:+.3f}*{k}" for k, v in model.params.drop('const').items()))
STEP 1 Data audit
missing p1 median p99 max
engine_size 0 0.80 1.70 2.60 2.60
horsepower 0 49.93 105.00 872.40 1150.00
curb_weight 5 987.86 1314.00 1627.66 1714.00
length_mm 0 3825.98 4188.50 4615.34 4666.00
fuel_capacity 0 42.20 50.15 57.60 60.20
fuel_efficiency 8 17.39 21.75 25.70 26.00
price_lakh 0 4.76 10.66 17.97 94.70
resale_value_lakh 35 2.37 7.03 12.76 14.67
STEP 2 Train/test split 70:30 -> train 140 cars, test 60 cars
STEP 3 Three outlier rules for horsepower (train): IQR fences [40, 169] | mean +/- 3 SD [-242, 484] | percentiles [54, 819]
the 99th percentile still sits inside the errors (more than 1% of rows are wrong), so cap with the IQR fences
capped every numeric column at its train IQR fences: 3 horsepower values capped, max 1150 -> 169
STEP 4 12 missing resale values in test: average error SimpleImputer(median) 1.60 lakh | KNNImputer(k=5) 0.94 lakh -> using KNNImputer
STEP 5 One-hot encoding -> 17 features; target ln(sales): skew 1.00 -> 0.09
STEP 6 VIF elimination (multicollinearity), protecting ['price_lakh']
drop curb_weight VIF = 9.7
drop engine_size VIF = 7.2
kept 15 features, max VIF 3.75
STEP 7 OLS with all VIF-screened features: 15 features, adjusted R2 on train 0.778
RMSE MAPE R2
train 13.38 13.0% 0.809
test 16.15 16.7% 0.792
verdict: good fit: train and test errors are close
STEP 8 OLS with significant drivers only: 4 features, adjusted R2 on train 0.784
RMSE MAPE R2
train 13.53 12.8% 0.805
test 15.80 16.1% 0.801
verdict: good fit: train and test errors are close
driver coef effect on sales per unit
fuel_capacity +0.010 about +1.0%
fuel_efficiency +0.097 about +10.2%
price_lakh -0.102 about -9.7%
vehicle_type_SUV +0.182 about +20.0%
equation: ln(sales) = 2.76 +0.010*fuel_capacity +0.097*fuel_efficiency -0.102*price_lakh +0.182*vehicle_type_SUV
5. Reading the output
- The data contains real-world problems on purpose: missing resale, efficiency and weight values, and data-entry errors (an extra zero in horsepower and price).
- Step 3 shows why the rule matters: the 99th percentile (819 hp) sits inside the errors, while the IQR fence (169 hp) removes them.
- Step 4 compares the two imputers on the test rows: KNN is closer to the expected resale value because it uses similar cars.
- Step 6 drops curb weight and engine size (strongly tied to price and each other) but protects price, the lever the client controls.
- Steps 7 and 8 show train and test errors close together: a good fit. The final model keeps four drivers and reads simply: each lakh of price cuts sales by about 10%, an SUV adds about 20%.
6. Common mistakes
| Mistake | Do this instead |
|---|---|
| Capping or imputing before the split | Test information leaks into training. Fit every treatment on train only. |
| Dropping a key business variable for VIF | Protect it and drop its correlated partners instead. |
| Reading log-model coefficients as units | In a log-target model a coefficient b means about (e^b - 1) x 100% change per unit. |
| Forgetting to align test dummies | Reindex test columns to the train columns, filling missing dummies with 0. |
| Reporting only R2 | Add RMSE or MAPE in business units, on the test set. |
7. Assignment
8. Interview questions
Why split before imputing?
Imputation values learned from the whole dataset contain test information, so test scores look better than they will be in production.
What is VIF and what threshold do you use?
Variance inflation factor, 1 / (1 - R2) of one X on the others; above 5 (some teams use 10) signals multicollinearity.
How do you interpret a coefficient of -0.10 on price in a log-sales model?
Each extra unit of price lowers sales by about 10% (e^-0.10 - 1 = -9.5%), holding the other variables fixed.
How do you know if the model overfits?
Test error much higher than train error. Fix with fewer features, regularisation or more data.