π Car Price Prediction Model
This repository hosts an optimized Machine Learning regression model designed to predict the market price of used cars based on various features such as vehicle age, mileage (kilometers driven), fuel type, transmission, owner type, and engine specifications.
The model is packaged alongside its pre-fitted scaler and column alignment artifacts to ensure seamless, consistent inference in production environments.
π¦ Saved Artifacts
To run predictions successfully, make sure you have the following three serialized files in your working directory:
model.pklβ The trained regression model (e.g., Random Forest, XGBoost, or Linear Regression).scaler.pklβ The fittedStandardScaler(orMinMaxScaler) used to normalize numerical features.columns.pklβ A serialized list of the exact feature columns (and their order) that the model expects, ensuring that One-Hot Encoded columns align perfectly during inference.
π οΈ How to Use (Inference)
You can load and test this model locally using the Python code snippet provided below.
Requirements
Ensure you have the necessary dependencies installed:
pip install scikit-learn joblib pandas numpy
Python Implementation
import joblib
import pandas as pd
import numpy as np
# 1. Load all serialized artifacts
model = joblib.load("model.pkl")
scaler = joblib.load("scaler.pkl")
model_columns = joblib.load("columns.pkl")
def predict_car_price(input_data_dict):
"""
input_data_dict: Dictionary containing raw user inputs.
Example: {'Year': 2018, 'Kilometers_Driven': 45000, 'Fuel_Type': 'Diesel', 'Transmission': 'Manual'}
"""
# Convert raw input dictionary to a DataFrame
df_temp = pd.DataFrame([input_data_dict])
# Perform One-Hot Encoding on categorical features
df_encoded = pd.get_dummies(df_temp)
# Reindex columns to match the training data layout, filling missing dummies with 0
df_aligned = df_encoded.reindex(columns=model_columns, fill_value=0)
# Identify numerical columns that require scaling (ensure this matches your training phase)
numerical_cols = ['Year', 'Kilometers_Driven'] # Add other scaled numerical columns here
# Apply the pre-fitted scaler to the numerical columns
df_aligned[numerical_cols] = scaler.transform(df_aligned[numerical_cols])
# Generate the price prediction
predicted_price = model.predict(df_aligned)[0]
return round(predicted_price, 2)
# Execution Example
sample_car = {
'Year': 2018,
'Kilometers_Driven': 45000,
'Fuel_Type_Diesel': 1, # Represents 'Diesel' under One-Hot Encoding
'Transmission_Manual': 1 # Represents 'Manual' under One-Hot Encoding
}
# Predict Price (Make sure your sample structure matches your column list)
price_est = predict_car_price(sample_car)
print(f"Estimated Car Price: ${price_est}")
π Training & Preprocessing Pipeline
Data Preprocessing steps implemented:
- Handling Missing Values: Null values in numerical fields (like Mileage/Engine) were imputed using median values, while categorical nulls were filled with mode/constant strategies.
- Feature Scaling: Continuous variables were normalized using a
StandardScalerto bring them onto a uniform scale. - Categorical Encoding: One-Hot Encoding was applied to non-numeric columns (
Fuel_Type,Transmission, etc.). - Column State Persistence: The exact column configuration was saved into
columns.pklto prevent structure misalignment errors during live deployments (such as Streamlit or FastAPI).
Key Performance Metrics:
- R-squared (R2) Score: ~89% (Update this with your actual test score)
- Mean Absolute Error (MAE): Low average absolute variance from true market prices.
π€ Contribution & Support
If you want to suggest optimizations, improve the preprocessing pipeline, or request feature additions, please feel free to open a Pull Request (PR) or raise a Github/HuggingFace Issue!
Evaluation results
- R-squared (R2) on Used Car Price Datasetself-reported0.890