Velamuvi AIAcademy

Lesson 13 of 13 · Project

Project: Predict House Prices

A complete beginner ML project in Python: explore house sales, encode features, split the data, beat a baseline with linear regression and a decision tree.

  • 6 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • Run a complete machine learning project from data to prediction
  • Explore data and turn it into features and labels
  • Compare models against a baseline on a test set
  • Read what the model learned and use it on a new house

The task

An estate agent wants a quick estimate of a house's price from four facts: size, number of bedrooms, age and area (city, suburbs or village). You'll follow the workflow from the previous lesson, using 300 past sales.

The dataset here is generated by code, so everyone gets the same numbers and you can see the hidden rules that produced it. That lets you check whether the model learns them. Real data has the same shape: a table of examples with features and a label.

Step 1: explore the data

Try it yourselfPython
import random

# ---- Make a realistic practice dataset of 300 house sales ----
rng = random.Random(42)
AREA_PREMIUM = {"city": 80_000, "suburbs": 40_000, "village": 0}
houses = []
for _ in range(300):
    size = rng.randint(40, 200)                          # square metres
    bedrooms = max(1, min(6, size // 30 + rng.randint(-1, 1)))
    age = rng.randint(0, 80)                             # years
    area = rng.choice(["city", "suburbs", "village"])
    price = 50_000 + 2_200 * size + 15_000 * bedrooms - 800 * age + AREA_PREMIUM[area]
    price += rng.randint(-30_000, 30_000)                # things the data doesn't capture
    houses.append({"size": size, "bedrooms": bedrooms, "age": age, "area": area, "price": price})

# ---- Explore before modelling ----
print("First 3 houses:")
for h in houses[:3]:
    print("  ", h)

print("\nAverage price by area:")
for area in ["city", "suburbs", "village"]:
    prices = [h["price"] for h in houses if h["area"] == area]
    print(f"   {area:<8} {sum(prices) / len(prices):>9,.0f}  ({len(prices)} houses)")

sizes = [h["size"] for h in houses]
print(f"\nSizes range from {min(sizes)} to {max(sizes)} m²")

Three things to notice:

  • Prices range widely, so a good model must use the features.
  • Village houses are cheaper on average.
  • City and suburban averages are almost the same, even though the hidden rules give city houses a bigger premium. Simple averages mix in other differences (here, the city houses in this sample happen to be smaller: 115 m² on average, against 132 m² in the suburbs). A model that looks at all the features together can separate these effects.

Steps 2–5: features, split, baseline, models

Try it yourselfPython
import random

# ---- Make a realistic practice dataset of 300 house sales ----
rng = random.Random(42)
AREA_PREMIUM = {"city": 80_000, "suburbs": 40_000, "village": 0}
houses = []
for _ in range(300):
    size = rng.randint(40, 200)                          # square metres
    bedrooms = max(1, min(6, size // 30 + rng.randint(-1, 1)))
    age = rng.randint(0, 80)                             # years
    area = rng.choice(["city", "suburbs", "village"])
    price = 50_000 + 2_200 * size + 15_000 * bedrooms - 800 * age + AREA_PREMIUM[area]
    price += rng.randint(-30_000, 30_000)                # things the data doesn't capture
    houses.append({"size": size, "bedrooms": bedrooms, "age": age, "area": area, "price": price})

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor

# ---- 1. Features and labels (one-hot encode the area) ----
AREAS = ["city", "suburbs", "village"]
def features(h):
    return [h["size"], h["bedrooms"], h["age"]] + [1 if h["area"] == a else 0 for a in AREAS]

X = [features(h) for h in houses]
y = [h["price"] for h in houses]

# ---- 2. Split: 80% to train, 20% to test ----
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

def mae(predictions, actual):
    return sum(abs(p - a) for p, a in zip(predictions, actual)) / len(actual)

# ---- 3. Baseline: always predict the average training price ----
average = sum(y_train) / len(y_train)
print(f"Baseline (average price):  MAE {mae([average] * len(y_test), y_test):>8,.0f}")

# ---- 4. Train two models and compare on the test set ----
models = {
    "Linear regression": LinearRegression(),
    "Decision tree (depth 4)": DecisionTreeRegressor(max_depth=4, random_state=0),
}
for name, model in models.items():
    model.fit(X_train, y_train)
    print(f"{name + ':':<26} MAE {mae(model.predict(X_test), y_test):>8,.0f}")

# ---- 5. Look inside the best model, then use it on a new house ----
best = models["Linear regression"]
size_w, bedroom_w, age_w = best.coef_[:3]
print(f"\nLearned: each m² adds {size_w:,.0f}, each bedroom {bedroom_w:,.0f}, each year of age {age_w:,.0f}")
new_house = {"size": 110, "bedrooms": 3, "age": 15, "area": "suburbs"}
print(f"Predicted price for {new_house}:")
print(f"   {best.predict([features(new_house)])[0]:,.0f}")

Reading the results:

  • Baseline: always guessing the average price is off by about 108,000. That's the number to beat.
  • Linear regression: off by about 17,000, more than six times better than the baseline.
  • Decision tree: off by about 30,000. Better than the baseline, but a depth-4 tree can only give 16 different prices, which is too coarse for this smooth pattern.
  • What it learned: about 2,100 per square metre, 16,800 per bedroom and minus 860 per year of age, close to the hidden rules (2,200, 15,000 and minus 800). The remaining differences come from the random noise in prices.

Things to try

Change the code above and run it again:

  1. Set max_depth to 2, then 8. What happens to the tree's error? Which value overfits?
  2. Remove the age feature from features. How much worse does the linear model get?
  3. Change test_size to 0.5. The model trains on fewer houses: does it still learn similar weights?
  4. Predict a price for your own imaginary house.

Common mistakes

Practice exercise

Evaluate a house price model: compute its MAE and check it against the baseline.

Your solutionPython
actual    = [320_000, 275_000, 410_000, 198_000]
predicted = [305_000, 290_000, 425_000, 213_000]
baseline_mae = 70_000

# Print the model's mean absolute error with thousands separators,
# then whether it beats the baseline, like:
# Model MAE: 12,345
# Beats baseline: yes
Knowledge check

The baseline's error is 107,610 and the linear model's is 16,809 on the same test set. What can you conclude?

Summary

  • You ran a full project: explore, build features and labels, split, set a baseline, train, evaluate, predict.
  • Linear regression beat the baseline by a wide margin and recovered rules close to the hidden ones.
  • Comparing models on test data shows which works best for this data.
  • Models are reliable only for cases similar to their training data.

Course complete

You now know what machine learning is, the main types, how data is organised into features and labels, why we split data, how models make predictions, how to recognise overfitting, underfitting, bias and variance, how to measure models, and the workflow every project follows. Next, the Supervised Learning course looks at the core algorithms in depth.

Finished reading? Tick it off to track your progress.