Machine Learning project 18
Machine Learning Car Price Prediction Project
Build and evaluate a complete car price prediction workflow with reproducible Python code, explicit metrics, and honest limitations.
Explore Machine Learning training in VizagView all project ideas
Dataset and objective
A reproducible synthetic used-car table with age, kilometres, brand segment, fuel, transmission, and price.
Skills practised
- Mixed tabular regression
- One-hot encoding
- Random forests
- Valuation limitations
Requirements
- Python 3.10 or later
- A terminal or command prompt
python -m pip install numpy pandas scikit-learn- About 45-60 minutes to build and review
Machine Learning workflow
- Data: A reproducible synthetic used-car table with age, kilometres, brand segment, fuel, transmission, and price.
- Preprocessing: OneHotEncoder handles categorical fields while numeric fields pass through a ColumnTransformer.
- Model: RandomForestRegressor captures nonlinear depreciation and feature interactions.
- Evaluation: MAE in synthetic INR and R-squared on a 25% holdout set.
Complete Python code
Save the code as ml_car_price_prediction.py. The random state and data handling are included so the result can be reproduced and reviewed.
"""Predict synthetic used-car prices with a mixed-feature regression pipeline."""
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder
def make_demo_data(rows: int = 3500, random_state: int = 42) -> pd.DataFrame:
rng = np.random.default_rng(random_state)
age = rng.integers(0, 16, rows)
kilometres = np.maximum(500, age * rng.normal(12_000, 3000, rows) + rng.normal(8000, 6000, rows))
brand = rng.choice(["budget", "midrange", "premium"], rows, p=[0.45, 0.4, 0.15])
fuel = rng.choice(["petrol", "diesel", "hybrid", "electric"], rows, p=[0.48, 0.28, 0.14, 0.10])
transmission = rng.choice(["manual", "automatic"], rows, p=[0.55, 0.45])
brand_value = pd.Series(brand).map({"budget": 0, "midrange": 350_000, "premium": 1_200_000}).to_numpy()
fuel_value = pd.Series(fuel).map({"petrol": 0, "diesel": 80_000, "hybrid": 300_000, "electric": 450_000}).to_numpy()
price = 1_000_000 + brand_value + fuel_value + 120_000 * (transmission == "automatic") - 65_000 * age - 2.2 * kilometres + rng.normal(0, 110_000, rows)
price = np.maximum(price, 80_000)
return pd.DataFrame({
"age_years": age,
"kilometres": kilometres,
"brand_segment": brand,
"fuel": fuel,
"transmission": transmission,
"price": price,
})
def train_model(random_state: int = 42):
data = make_demo_data(random_state=random_state)
x, y = data.drop(columns="price"), data["price"]
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=random_state)
categories = ["brand_segment", "fuel", "transmission"]
preprocessing = ColumnTransformer([
("categories", OneHotEncoder(handle_unknown="ignore"), categories),
], remainder="passthrough")
model = make_pipeline(
preprocessing,
RandomForestRegressor(n_estimators=250, min_samples_leaf=3, random_state=random_state, n_jobs=-1),
)
model.fit(x_train, y_train)
predictions = model.predict(x_test)
return model, mean_absolute_error(y_test, predictions), r2_score(y_test, predictions)
def main() -> None:
_, mae, r2 = train_model()
print("Synthetic Used-Car Price Regression")
print(f"MAE: INR {mae:,.0f}")
print(f"R-squared: {r2:.3f}")
print("Synthetic education only—real valuation needs verified local listings, condition, trim, history, and market date.")
if __name__ == "__main__":
main()
How the pipeline works
OneHotEncoder handles categorical fields while numeric fields pass through a ColumnTransformer.
RandomForestRegressor captures nonlinear depreciation and feature interactions. MAE in synthetic INR and R-squared on a 25% holdout set.
Run the project
- Create and activate a virtual environment.
- Install the dependencies with
python -m pip install numpy pandas scikit-learn. - Run
python ml_car_price_prediction.py. - Review every printed metric together with the limitation below; a single score never proves deployment readiness.
How to interpret the evaluation
Classification projects report class-aware metrics so majority classes do not hide weak performance. Regression projects report errors in target units and include R-squared or a simple baseline where appropriate. Always verify the split strategy matches how new data will arrive.
Accuracy, ethics, and safety limits
Synthetic education only. Real prices depend on model, trim, location, condition, history, ownership, inspection, market date, and verified listings.
Ways to extend the project
Use licensed marketplace data, add model year and trim, prevent listing duplicates across splits, model price date, inspect residuals, and quantify uncertainty.
Continue learning Machine Learning
Try the next project, return to the Softenant project library, or explore the Machine Learning course in Vizag for guided data preparation, model evaluation, and portfolio feedback.