House Price Prediction using Machine Learning
House Price Prediction using Machine Learning
Predicting housing prices is one of the most popular beginner-friendly Machine Learning projects because it introduces almost every important concept in a real-world ML workflow.
In this project, I built an end-to-end Machine Learning pipeline using Scikit-Learn that:
- Cleans missing values
- Encodes categorical features
- Scales numerical features
- Trains a Random Forest Regressor
- Saves the trained model
- Performs inference on unseen data
Rather than focusing only on model accuracy, this project emphasizes building a reusable and production-friendly pipeline.
Project Workflow
The complete workflow looks like this:
Housing Dataset
│
▼
Train-Test Split
│
▼
Data Preprocessing
│
▼
Feature Engineering
│
▼
Pipeline
│
▼
Random Forest Regressor
│
▼
Save Model
│
▼
Prediction
Step 1 — Importing Libraries
Every Machine Learning project begins by importing the required libraries.
import joblib
import os
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestRegressor
from sklearn.impute import SimpleImputer
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
Why these libraries?
- Pandas → Data manipulation
- NumPy → Numerical computations
- Scikit-Learn → Machine Learning framework
- Joblib → Saving trained models
- Pipeline → Automating preprocessing
Step 2 — Loading the Dataset
The housing dataset is loaded into a Pandas DataFrame.
housing = pd.read_csv("housing.csv")
Before training any model, it is important to understand the dataset and inspect missing values, numerical columns, and categorical features.
Step 3 — Creating Stratified Train-Test Split
Instead of performing a random split, this project uses StratifiedShuffleSplit.
Why?
Because income has a strong relationship with house prices.
We first create income categories.
housing["Income_Category"] = pd.cut(
housing["median_income"],
bins=[0, 1.5, 3.0, 4.5, 6.0, np.inf],
labels=[1,2,3,4,5]
)
Then perform the split.
split = StratifiedShuffleSplit(
n_splits=1,
test_size=0.2,
random_state=42
)
This ensures that both training and testing datasets contain similar income distributions.
Step 4 — Separating Features and Labels
Our target variable is the house price.
housing_labels = housing_training["median_house_value"].copy()
The remaining columns become input features.
housing_features = housing_training.drop(
"median_house_value",
axis=1
)
Next, we identify numerical and categorical columns.
num_attributes = housing_features.drop(
"ocean_proximity",
axis=1
).columns.tolist()
cat_attributes = ["ocean_proximity"]
Step 5 — Data Preprocessing
Real-world datasets contain missing values and categorical features.
Machine Learning models cannot work directly with such data.
We therefore build two preprocessing pipelines.
Numerical Pipeline
num_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler())
])
This pipeline:
- Replaces missing values using the median
- Standardizes every numerical feature
Categorical Pipeline
cat_pipeline = Pipeline([
("onehot", OneHotEncoder(handle_unknown="ignore"))
])
This converts text labels into numerical vectors.
Step 6 — Combining Both Pipelines
The numerical and categorical pipelines are merged using a ColumnTransformer.
full_pipeline = ColumnTransformer([
("num", num_pipeline, num_attributes),
("cat", cat_pipeline, cat_attributes)
])
Finally,
housing_prepared = full_pipeline.fit_transform(
housing_features
)
At this point the dataset is fully transformed and ready for model training.
Step 7 — Training the Model
For this project I selected a Random Forest Regressor.
model = RandomForestRegressor()
Training the model is straightforward.
model.fit(
housing_prepared,
housing_labels
)
Random Forest performs well on structured tabular datasets and usually requires little feature engineering.
Step 8 — Saving the Model
Instead of retraining every time, we serialize the model.
joblib.dump(model, MODEL_FILE)
joblib.dump(pipeline, PIPELINE_FILE)
Now both the trained model and preprocessing pipeline can be reused.
Step 9 — Running Inference
If the model already exists, we simply load it.
model = joblib.load(MODEL_FILE)
pipeline = joblib.load(PIPELINE_FILE)
Read unseen data.
input_data = pd.read_csv("input.csv")
Transform it.
transformed_input = pipeline.transform(input_data)
Generate predictions.
predictions = model.predict(transformed_input)
Store predictions.
input_data["median_house_value"] = predictions
Finally,
input_data.to_csv("output.csv", index=False)
The generated CSV now contains predicted housing prices.
Final Project Structure
HousePricePrediction/
│
├── housing.csv
├── input.csv
├── output.csv
│
├── model.pkl
├── pipeline.pkl
│
└── main.py
Key Learnings
Through this project I learned:
- Building reusable preprocessing pipelines
- Handling missing values
- Encoding categorical features
- Feature scaling
- Stratified train-test splitting
- Training Random Forest models
- Model serialization using Joblib
- Running inference on unseen data
Conclusion
This project demonstrates a complete Machine Learning workflow—from raw data to a trained model capable of making predictions on unseen samples.
While the model itself is relatively simple, the emphasis is on writing clean, reusable, and production-friendly code using Scikit-Learn Pipelines. These practices become even more valuable as projects grow in complexity and move toward deployment.