Skip to main content

California Housing - End-to-End Machine Learning Pipeline

Project Overview

This project demonstrates a complete machine learning workflow for tabular regression using the California Housing dataset.

What we will build

Technologies

  • Python
  • NumPy
  • Pandas
  • Matplotlib
  • Scikit-learn
  • Joblib
  • Jupyter Notebook

Step 1 — Import Libraries

Purpose

Import all libraries required for data processing, visualization, machine learning, evaluation, and model persistence.

Key libraries


Step 2 — Load California Housing Dataset

Purpose

Load the California Housing dataset provided by scikit-learn.

Expected output

The dataset contains:
  • 20,640 observations
  • 8 input features
  • 1 target variable

Step 3 — View the Dataset

Purpose

Inspect the first few rows to understand the structure of the dataset.

Important columns


Step 4 — Inspect Dataset Information

Purpose

Check data types, number of entries, and memory usage.

Why?

Before building a model, we need to know:

Step 5 — Statistical Summary

Purpose

Understand the distribution of numerical features.
This provides:
  • Mean
  • Standard deviation
  • Minimum
  • 25th percentile
  • Median
  • 75th percentile
  • Maximum

Step 6 — Check Missing Values

Purpose

Identify missing values before preprocessing.
If a column contains missing values, our pipeline will handle them using:

Step 7 — Separate Features and Target

Purpose

Separate input variables from the value we want to predict.

Concept

For this project:

Step 8 — Visualize Target Distribution

Purpose

Understand how the target variable is distributed.

Why?

Visualization helps identify:
  • Skewness
  • Extreme values
  • Distribution patterns

Step 9 — Create Feature Engineering Transformer

Purpose

Create additional features that may help the model learn relationships in the data. We create:

Why use a transformer?

Instead of manually modifying data, feature engineering becomes part of the ML pipeline.

Step 10 — Split Training and Testing Data

Purpose

Separate data used for learning from data used for final evaluation.

Split

random_state=42 makes the split reproducible.

Step 11 — Apply Feature Engineering Temporarily

Purpose

Determine which columns exist after feature engineering.
The original 8 features become 11 features.

Step 12 — Identify Numerical Features

Purpose

Tell the preprocessing pipeline which columns require numerical preprocessing.
These include:

Step 13 — Create Numerical Preprocessing Pipeline

Purpose

Build reusable preprocessing for numerical data.

Pipeline


Step 14 — Create ColumnTransformer

Purpose

Apply the numerical preprocessing pipeline to the numerical columns.
ColumnTransformer is useful when different groups of features need different preprocessing.

Step 15 — Build Linear Regression Pipeline

Purpose

Create the first regression model.

Pipeline structure


Step 16 — Train Linear Regression

Purpose

Fit the Linear Regression model using training data.
The model learns the relationship between:

Step 17 — Generate Linear Regression Predictions

Purpose

Use the trained model to predict values for unseen test data.
These predictions will be compared against:

Step 18 — Evaluate Linear Regression

Purpose

Measure the performance of Linear Regression.

Metrics


Step 19 — Create Random Forest Pipeline

Purpose

Train a nonlinear ensemble model.

Why Random Forest?

Random Forest can capture nonlinear relationships that Linear Regression may miss.

Step 20 — Train Random Forest

The model creates multiple decision trees and combines their predictions.

Step 21 — Generate Random Forest Predictions

The model predicts house values for the test set.

Step 22 — Evaluate Random Forest


Step 23 — Create Gradient Boosting Pipeline

Purpose

Add another powerful regression algorithm for comparison.
Gradient Boosting builds models sequentially, with later models focusing on previous errors.

Step 24 — Train Gradient Boosting


Step 25 — Generate Gradient Boosting Predictions


Step 26 — Evaluate Gradient Boosting


Step 27 — Create Model Comparison Table

Purpose

Compare all three models in one table.

Decision rule


Step 28 — Select Candidate for Tuning

Purpose

Choose the strongest model based on the comparison table. For this project, we will tune:
Why? Random Forest typically provides strong performance on tabular data and gives us several useful hyperparameters to optimize.

Step 29 — Define Hyperparameter Grid

Purpose

Define combinations of Random Forest parameters that GridSearchCV will test.

Important

Because the model is inside a pipeline:
is used. For example:
means:

Step 30 — Create GridSearchCV

Purpose

Automatically search through different hyperparameter combinations.

Configuration


Step 31 — Run GridSearchCV

Purpose

Train and evaluate all parameter combinations.
GridSearchCV performs:

Step 32 — Get Best Parameters

Purpose

Find the hyperparameters that performed best during cross-validation.
Example:
The actual result depends on the run.

Step 33 — Get Best Cross-Validation Score

The negative sign is required because scikit-learn represents loss/error scoring as negative values when using neg_root_mean_squared_error.

Step 34 — Extract Best Model

Purpose

Retrieve the complete tuned pipeline.
The resulting object includes:

Step 35 — Generate Final Predictions

Purpose

Use the optimized model on the test dataset.
The test set has not been used to select the hyperparameters, making it suitable for final evaluation.

Step 36 — Calculate Final MAE

Interpretation

MAE tells us the average absolute prediction error. Lower MAE is better.

Step 37 — Calculate Final RMSE and R²


Step 38 — Final Evaluation Summary

Purpose

Display all final metrics together.

Interpretation


Step 39 — Actual vs Predicted Plot

Purpose

Visually compare real house values against predictions.

Interpretation

The closer the points are to the diagonal line, the better the predictions.

Step 40 — Calculate Residuals

Purpose

Calculate prediction errors.
Formula:

Step 41 — Residual Plot

Purpose

Check whether prediction errors have an obvious pattern.

Good residual plot

Ideally:
Residuals should be reasonably scattered around zero.

Step 42 — Model RMSE Comparison Plot

Purpose

Visually compare model errors.

Interpretation

Lower RMSE indicates better performance.

Step 43 — Model R² Comparison Plot

Purpose

Compare the explained variance of each model.
Higher R² indicates better performance.

Step 44 — Save the Final Model

Purpose

Save the trained pipeline so it can be reused without retraining.
This creates:
Because feature engineering and preprocessing are inside the pipeline, the saved model contains the complete workflow.

Step 45 — Load the Saved Model

Purpose

Verify that the saved model can be loaded successfully.

Step 46 — Test the Loaded Model

Purpose

Make sure the saved model produces predictions correctly.
The loaded model should produce the same predictions as the original best_model. You can verify:
Expected:

Step 47 — Final Results and Project Summary

Final metrics table

Project conclusion

Add this as a Markdown cell:

Model Selection

Models were compared using: Random Forest was selected for hyperparameter tuning using GridSearchCV.

Results

Project Files

Installation

Run