Reading history

Machine Learning Project: House Price Prediction in Python

8 min read Updated 2 views

Build a house price prediction model in Python: pipelines, log-price ridge regression versus gradient boosting, test error in percent, feature importance and saving.

This project brings the regression lessons together. You will build a model that estimates the price of a flat from its size, location, age and other details. Along the way you will handle missing values and categories, compare two models fairly, check the winner on untouched test data, explain what drives its predictions and save it for later use.

In this project you will

  • Prepare numeric and text columns with a ColumnTransformer
  • Model a skewed target such as price on a log scale
  • Compare a linear model and gradient boosting with cross-validation
  • Report test error in units people understand
  • Explain the model with permutation importance and save it with joblib

This project uses ideas from pipelines, regression metrics, ridge regression and permutation importance.

The Complete Script

The data is made up so that the script runs anywhere without a download. It imitates flat sales in five areas of Dhaka, with prices in lakh taka (1 lakh = 100,000 taka).

import joblib
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer, TransformedTargetRegressor
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.impute import SimpleImputer
from sklearn.inspection import permutation_importance
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

# 1. Data: 2,500 made-up flat sales (price in lakh taka)
rng = np.random.default_rng(21)
n = 2500
df = pd.DataFrame({
    "area_sqft": rng.normal(1250, 350, n).clip(450, 3000).round(),
    "bedrooms": rng.integers(1, 5, n),
    "floor": rng.integers(1, 15, n),
    "age_years": rng.integers(0, 30, n),
    "has_lift": rng.choice([0, 1], n, p=[0.3, 0.7]),
    "area": rng.choice(["Gulshan", "Dhanmondi", "Mirpur", "Uttara", "Jatrabari"], n),
})
rate = df.area.map({"Gulshan": 25, "Dhanmondi": 17, "Uttara": 12,
                    "Mirpur": 8, "Jatrabari": 6.5})         # lakh per 100 sqft
df["price"] = (rate * df.area_sqft / 100 * (1 - 0.012 * df.age_years)
               * (1 + 0.08 * df.has_lift * (df.floor > 5))
               * rng.lognormal(0, 0.12, n)).round(1)
df.loc[rng.random(n) < 0.05, "age_years"] = np.nan          # some ages unknown
print(df.head(3).to_string())
print(f"Median price: {df.price.median():.0f} lakh")

# 2. Hold out 20% as a final test set
X, y = df.drop(columns="price"), df.price
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0)

# 3. Two candidate models, each a full pipeline
num = ["area_sqft", "bedrooms", "floor", "age_years", "has_lift"]
prep = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), num),
    ("cat", OneHotEncoder(handle_unknown="ignore"), ["area"]),
])
candidates = {
    "Ridge (log price)": TransformedTargetRegressor(
        make_pipeline(prep, Ridge()), func=np.log, inverse_func=np.exp),
    "Gradient boosting": make_pipeline(
        ColumnTransformer([("cat", OneHotEncoder(handle_unknown="ignore"), ["area"])],
                          remainder="passthrough"),
        HistGradientBoostingRegressor(random_state=0)),
}
cv_mae = {}
for name, model in candidates.items():
    cv_mae[name] = -cross_val_score(model, X_tr, y_tr, cv=5,
                                    scoring="neg_mean_absolute_error").mean()
    print(f"{name:18} CV MAE: {cv_mae[name]:.2f} lakh")
best_name = min(cv_mae, key=cv_mae.get)
print("Chosen:", best_name)

# 4. Final check on the untouched test set
best = candidates[best_name].fit(X_tr, y_tr)
pred = best.predict(X_te)
print(f"Test MAE: {mean_absolute_error(y_te, pred):.1f} lakh | R2: {r2_score(y_te, pred):.3f}")
print(f"Median error as % of price: {np.median(abs(pred - y_te) / y_te):.1%}")

# 5. Which inputs matter?
imp = permutation_importance(best, X_te, y_te, n_repeats=5, random_state=0)
for col, val in sorted(zip(X.columns, imp.importances_mean), key=lambda t: -t[1]):
    print(f"  {col:10} {round(val, 3) + 0.0:.3f}")

# 6. Save and reuse
joblib.dump(best, "flat_price_model.joblib")
loaded = joblib.load("flat_price_model.joblib")
flat = pd.DataFrame([{"area_sqft": 1400, "bedrooms": 3, "floor": 7, "age_years": 5,
                      "has_lift": 1, "area": "Dhanmondi"}])
print("Estimated price:", loaded.predict(flat).round(1), "lakh")

Output

   area_sqft  bedrooms  floor  age_years  has_lift     area  price
0     1376.0         3      7       29.0         0   Uttara  101.5
1     1779.0         2     10       13.0         1  Gulshan  422.1
2      625.0         2      2       26.0         1   Mirpur   33.1
Median price: 125 lakh
Ridge (log price)  CV MAE: 17.17 lakh
Gradient boosting  CV MAE: 17.18 lakh
Chosen: Ridge (log price)
Test MAE: 16.5 lakh | R2: 0.927
Median error as % of price: 9.1%
  area       1.502
  area_sqft  0.557
  age_years  0.101
  floor      0.003
  bedrooms   0.000
  has_lift   0.000
Estimated price: [227.2] lakh

Step by Step

1. The data

  • Price depends on area (Gulshan costs most per square foot, Jatrabari least), size, age, and a bonus for a lift on higher floors. Random noise of about 12% stands in for everything the data does not record, such as the view or the condition of the kitchen.
  • About 5% of ages are missing, as happens in real listings.
  • Prices range widely, from about 33 lakh to over 400 lakh in the first three rows alone. The median is 125 lakh.

2. Hold out a test set

20% of flats are set aside before any modelling. They are used once, at the very end.

3. Compare two models

  • The ridge pipeline fills missing ages with the median, scales the numbers and one-hot encodes the area. TransformedTargetRegressor trains it on the log of the price and converts predictions back with exp. Prices grow by percentages (a lift adds 8%, each year of age takes off 1.2%), and on a log scale those percentages become simple additions, which suits a linear model.
  • The gradient boosting pipeline only needs the area encoded. HistGradientBoostingRegressor handles missing values and different scales on its own.
  • Five-fold cross-validation on the training set gives a mean absolute error (MAE) of 17.17 lakh for ridge and 17.18 for boosting, a near tie. The script picks the lower one. When a simple model matches a complex one, prefer the simple one: it is faster and easier to explain.

4. Test once

  • On the untouched test set, the MAE is 16.5 lakh and R² is 0.927, close to the cross-validation estimate. That agreement is a good sign the model was not overfitted to the training data.
  • MAE in lakh means little on its own when prices range from 30 to 400 lakh. The median percentage error, 9.1%, is easier to communicate: “a typical estimate is within about 9% of the real price”. The 12% random noise built into the data would on its own cause a typical error of about 8%, so there is little left for any model to learn.

5. Explain

Permutation importance shuffles one column at a time and measures how much the R² score drops. Area matters most, then size, then age. Floor, bedrooms and lift barely register. The lift bonus only applies above the fifth floor and is small next to the noise, while bedrooms had no effect at all when the data was made.

6. Save and reuse

joblib.dump saves the whole pipeline, including the imputer, scaler and encoder. The loaded model accepts a raw table with the original column names and estimates 227.2 lakh for a 1,400 sqft, 5-year-old Dhanmondi flat on the 7th floor with a lift.

Taking It Further

  • Add a 10% to 90% price range with quantile regression, so buyers see a range instead of one number.
  • Add features such as distance to the main road or the number of parking spaces.
  • Tune the boosting model with grid search and see whether it pulls ahead.
  • Plot predicted against actual prices to spot areas where the model is consistently too high or too low.

Common Mistakes in Price Models

  1. Scoring with R² alone. Also report an error in money or percent, which people can act on.
  2. Leaking the future. With real sales, train on older sales and test on newer ones, because prices change over time.
  3. Using features that are only known after the sale, such as a registration fee calculated from the sale price. The model looks brilliant in testing and is useless for new flats.
  4. Ignoring outliers such as typing errors in the area (12,000 sqft instead of 1,200). Check the largest errors one by one.

Practice Exercises

Exercise 1. Print the five test flats with the largest percentage error.

Show answer
report = X_te.assign(price=y_te, predicted=pred.round(1),
                     pct_error=(abs(pred - y_te) / y_te).round(3))
print(report.sort_values("pct_error", ascending=False).head())

Exercise 2. Estimate the price of the same Dhanmondi flat in Mirpur instead.

Show answer
print(loaded.predict(flat.assign(area="Mirpur")).round(1))

The estimate falls to roughly half, because the Mirpur price per square foot in this data is less than half the Dhanmondi price.

Frequently Asked Questions

Why predict the log of the price?

Prices are skewed: a few flats cost far more than the rest. On a log scale the spread is more even, percentage effects become additive, and the model is not dominated by the most expensive flats.

Can I use this code with real listings?

Yes. Replace step 1 with pd.read_csv on your own data and keep the same column names, or update the num list and the category column. Check for missing values and typing errors first.

Summary

  • Put all preparation inside pipelines so cross-validation and saving stay correct.
  • Model skewed prices on a log scale with TransformedTargetRegressor.
  • Compare models with cross-validation, then test the winner once.
  • Report errors in money and percent, and explain the model with permutation importance.

Next: Data Leakage in Machine Learning.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *