<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Azzeddine's AI Engineering Blog]]></title><description><![CDATA[Azzeddine's AI Engineering Blog]]></description><link>https://azzeddine.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 21:09:36 GMT</lastBuildDate><atom:link href="https://azzeddine.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[# Building and Deploying an End-to-End Car Price Predictor with Python, Scikit-Learn, and Streamlit]]></title><description><![CDATA[Have you ever wondered how online marketplaces instantly estimate the market value of a used car? As part of my AI and Data Engineering learning journey, I…]]></description><link>https://azzeddine.hashnode.dev/building-and-deploying-an-end-to-end-car-price-predictor-with-python-scikit-learn-and-streamlit</link><guid isPermaLink="true">https://azzeddine.hashnode.dev/building-and-deploying-an-end-to-end-car-price-predictor-with-python-scikit-learn-and-streamlit</guid><category><![CDATA[Python]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[streamlit]]></category><category><![CDATA[Data Science]]></category><dc:creator><![CDATA[Azzeddine-Mahmoudi]]></dc:creator><pubDate>Thu, 12 Nov 2026 14:19:50 GMT</pubDate><content:encoded><![CDATA[<p>Have you ever wondered how online marketplaces instantly estimate the market value of a used car?</p>
<p>As part of my AI and Data Engineering learning journey, I set out to build a fully functional, end-to-end Machine Learning web application from scratch. The goal was simple: take raw automotive market data, clean and preprocess it, train a robust regression model, serialize it, and deploy it live on the cloud so anyone can calculate a car's price in seconds.</p>
<p>Here is a complete walkthrough of how I built the <strong>Car Price Predictor</strong>, the data engineering pipeline behind it, and how I brought it to life with <strong>Streamlit</strong>.</p>
<hr />
<h2>1. The Dataset &amp; Data Engineering Pipeline</h2>
<p>For this project, I worked with a comprehensive used car dataset covering dealer listings across the US and Canada (<code>ca-dealers-used.csv</code>, originally over 393,000 rows). Real-world data is notoriously messy, containing missing values, inconsistent casing, and redundant columns.</p>
<p>Using <strong>pandas</strong>, I built an end-to-end cleaning and feature engineering script:</p>
<ul>
<li><strong>Dropping Redundant Features:</strong> Columns like <code>id</code>, <code>vin</code>, <code>stock_no</code>, <code>trim</code>, <code>seller_name</code>, and specific street addresses were dropped as they carry no predictive value for general pricing.</li>
<li><strong>Standardizing Categorical Strings:</strong> Standardized string values for features like <code>make</code> and <code>body_type</code> using lowercasing and uniform replacement conventions:</li>
</ul>
<pre><code class="language-python">df['make'] = df['make'].apply(lambda x : x.lower().replace(' ', '_').replace('-', '_'))
df['body_type'] = df['body_type'].apply(lambda x : x.lower().replace(' ', '_').replace('-', '_'))
</code></pre>
<ul>
<li><strong>Feature Engineering Fuel Types:</strong> The raw dataset contained 23 distinct, fragmented fuel descriptions (such as <code>E85 / Unleaded</code> and <code>Electric / Premium Unleaded</code>). I grouped them into four clean, generalized categories (<code>gasoline</code>, <code>hyrid</code>, <code>biodiesel</code>, <code>other</code>) to help the model learn stable patterns.</li>
<li><strong>Filtering Rare Models:</strong> Filtered out single-occurrence make/model combinations to ensure reliable stratified train-test splitting, leaving 269,493 clean records.</li>
</ul>
<hr />
<h2>2. Training the Machine Learning Model</h2>
<p>To predict a continuous target variable (<code>price</code>), I implemented a machine learning pipeline using <strong>Scikit-Learn</strong>:</p>
<ul>
<li><strong>Stratified Train-Test Split:</strong> Split the dataset (80% training, 20% testing) stratified by <code>make</code> and <code>model</code> so both sets maintained representative distributions across all vehicle types.</li>
<li><strong>Preprocessing Column Transformer:</strong> Built a <code>ColumnTransformer</code> combining median imputation for numerical features (<code>miles</code>, <code>year</code>, <code>engine_size</code>) and most-frequent imputation plus <code>OneHotEncoder</code> (with <code>handle_unknown="ignore"</code>) for categorical features.</li>
<li><strong>Model Choice &amp; Log Target Transformation:</strong> Trained a <code>HistGradientBoostingRegressor</code> wrapped inside a <code>TransformedTargetRegressor</code> (applying a <code>np.log1p</code> transformation on prices and <code>np.expm1</code> on predictions) to handle skewed vehicle price distributions and capture non-linear relationships effectively:</li>
</ul>
<pre><code class="language-python">regr = HistGradientBoostingRegressor(random_state=42)

model = TransformedTargetRegressor(
    regressor=Pipeline([("pre", pre), ("regr", regr)]),
    func=np.log1p, inverse_func=np.expm1
)
</code></pre>
<ul>
<li><strong>Model Evaluation:</strong> Evaluated performance on the held-out 20% test split, achieving strong regression metrics (\(R^2 = 0.890\), \(\text{RMSE} = 6493.4\), \(\text{MAE} = 2920.4\)):</li>
</ul>
<pre><code class="language-python">mae = mean_absolute_error(y_test, y_pred)
rmse = root_mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f"R²={r2:.3f}, RMSE={rmse:.1f}, MAE={mae:.1f}")
# Output: R²=0.890, RMSE=6493.4, MAE=2920.4
</code></pre>
<ul>
<li><strong>Model Serialization:</strong> Once evaluated, I saved the trained pipeline to disk using <strong>Joblib</strong> so it could be loaded instantly into the web application:</li>
</ul>
<pre><code class="language-python">from joblib import dump
dump(model, 'model/model.joblib')
</code></pre>
<hr />
<h2>3. Bringing It to Life with Streamlit</h2>
<p>A machine learning model is only as powerful as its accessibility. To make it interactive, I built a clean user interface using <strong>Streamlit</strong>.</p>
<p>By combining session state management (<code>st.session_state</code>), resource caching (<code>@st.cache_resource</code>), and a three-column reactive form layout, the app loads the model once and provides an intuitive dashboard for users:</p>
<pre><code class="language-python">import streamlit as st
import numpy as np
from joblib import load
import pandas as pd

# Initialize session state for predictions
if "pred" not in st.session_state:
    st.session_state["pred"] = None

# Cached model loader
@st.cache_resource(show_spinner="Loading Model...")
def load_model():
    return load("model/model.joblib")

# Prediction callback function
def make_prediction(pipe):
    X_pred = pd.DataFrame([{
        "miles": st.session_state["miles"],
        "year": st.session_state["year"],
        "make": st.session_state["make"],
        "model": st.session_state["model"],
        "body_type": st.session_state["body_type"],
        "vehicle_type": st.session_state["vehicle_type"],
        "drivetrain": st.session_state["drivetrain"],
        "transmission": st.session_state["transmission"],
        "fuel_type": st.session_state["fuel_type"],
        "engine_size": st.session_state["engine_size"],
        "engine_block": st.session_state["engine_block"],
        "state": st.session_state["province"]
    }])
    pred = pipe.predict(X_pred)
    st.session_state["pred"] = round(pred[0], 2)

if __name__ == "__main__":
    st.title("Prediction Car Price")
    pipe = load_model()

    with st.form(key="form"):
        col1, col2, col3 = st.columns(3)
        with col1:
            st.number_input("Miles", value=86132.0, min_value=0.0, step=0.1, key="miles")
            st.selectbox("Model", index=0, key="model", options=['Prius', 'Highlander', 'Civic', 'Accord', 'Corolla'])
            # ... additional vehicle input controls ...
        
        st.form_submit_button("Calculate", type="primary", on_click=make_prediction, kwargs=dict(pipe=pipe))

    if st.session_state["pred"] is not None:
        st.subheader(f"Predicted Price of Reused Car: ${st.session_state['pred']}")
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6af5acbd1e48a3cfb7a29d02/40a58dcd-2e8c-49bb-a06e-dec3167d0123.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>4. Cloud Deployment &amp; Key Takeaways</h2>
<p>Deploying the app live to <strong>Streamlit Community Cloud</strong> taught me several valuable engineering lessons:</p>
<ol>
<li><strong>Dependency Alignment:</strong> Ensuring a precise <code>requirements.txt</code> file specifying compatible package versions (such as <code>scikit-learn==1.4.2</code>) is vital to prevent serialization mismatch errors during cloud builds.</li>
<li><strong>Version Control:</strong> Maintaining clean, incremental commit habits on GitHub (<code>git add</code>, <code>git commit</code>, <code>git push</code>) kept the codebase synchronized and enabled seamless continuous deployment.</li>
</ol>
<hr />
<h3>Check Out the Project</h3>
<ul>
<li><strong>Live App:</strong> <a href="https://your-streamlit-app-url.streamlit.app">Try the Live Car Price Predictor</a> <em>(</em><a href="https://car-price-predictor-hhutychgwzvuxzzze5b9eo.streamlit.app/">https://car-price-predictor-hhutychgwzvuxzzze5b9eo.streamlit.app/</a><em>)</em></li>
<li><strong>GitHub Repository:</strong> <a href="https://github.com/Azzeddine-Mahmoudi/Car-price-predictor">Explore the Source Code on GitHub</a>, <a href="https://github.com/Azzeddine-Mahmoudi/car-price-predictor.git">https://github.com/Azzeddine-Mahmoudi/car-price-predictor.git</a></li>
<li><strong>Video Walkthrough:</strong> <a href="https://youtube.com">Watch the YouTube Demo</a> <em>(Coming soon)</em></li>
</ul>
]]></content:encoded></item></channel></rss>