Guided project · Foundations · Algorithms in detail

Your first machine learning model: predict house prices

Train, test and improve a real machine learning model on real housing data, one small code cell at a time.

About 75 minIntermediateCopy-paste code
0 of 10 steps done

What you'll build

A model that predicts house prices in California from things like income and rooms, and a comparison of two algorithms.

What you'll learn

  • Loading and exploring a dataset
  • Splitting data into training and test sets
  • Training linear regression and random forest
  • Measuring error and making a prediction

You'll need

Google Colab (free, runs in your browser with a Google account). No installation.

Create a free account to unlock this project

The step-by-step instructions, copy-ready prompts, progress tracker and portfolio texts are for members. It's free, takes under a minute, and unlocks all guided projects.

Want to try first? These projects are open to everyone: Prompt lab and One idea, five posts.

Before you start

Use any free AI chatbot (ChatGPT, Claude, Gemini or Copilot). Never paste private or confidential information.

Step by step

  1. Open a notebook

    Go to colab.research.google.com, sign in and click New notebook.

    You should see: An empty notebook with one code cell.

  2. Load the data

    Paste this into the first cell and run it. It downloads a free dataset of about 20,000 California districts.

    Copy this code
    from sklearn.datasets import fetch_california_housing
    import pandas as pd
    
    data = fetch_california_housing(as_frame=True)
    df = data.frame
    df.head()

    You should see: A table with columns like MedInc (income), AveRooms and MedHouseVal (the price, in units of $100,000).

    Why it matters: Every ML project starts by looking at the data.

  3. Explore it

    Add a new cell (+ Code) and run this to see averages and the biggest influences on price.

    Copy this code
    print(df.describe().round(2))
    print(df.corr()['MedHouseVal'].sort_values(ascending=False))

    You should see: Summary numbers, and MedInc (income) near the top of the list: richer areas have pricier houses.

  4. Split into training and test data

    Keep 20% of the rows hidden so you can test the model honestly later.

    Copy this code
    from sklearn.model_selection import train_test_split
    
    X = df.drop(columns='MedHouseVal')   # the clues
    y = df['MedHouseVal']                # the answer to predict
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    print(len(X_train), len(X_test))

    You should see: Two numbers: about 16,500 rows for training and 4,100 for testing.

    Why it matters: Testing on data the model has never seen is the only honest way to judge it.

  5. Train linear regression

    Train the simplest model: a best-fit line through all the clues.

    Copy this code
    from sklearn.linear_model import LinearRegression
    from sklearn.metrics import mean_absolute_error
    
    lin = LinearRegression()
    lin.fit(X_train, y_train)
    print('Average error:', round(mean_absolute_error(y_test, lin.predict(X_test)), 3))

    You should see: An average error of roughly 0.53, i.e. predictions are off by about $53,000 on average.

  6. Try a random forest

    Now train hundreds of decision trees that vote together, and compare.

    Copy this code
    from sklearn.ensemble import RandomForestRegressor
    
    forest = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
    forest.fit(X_train, y_train)
    print('Average error:', round(mean_absolute_error(y_test, forest.predict(X_test)), 3))

    You should see: A smaller error, around 0.33. The forest captures patterns a straight line can't. It takes about a minute.

    Why it matters: Trying more than one algorithm and comparing them on the same test data is standard practice.

  7. See predictions vs reality

    Plot predicted prices against real prices for the test houses.

    Copy this code
    import matplotlib.pyplot as plt
    
    pred = forest.predict(X_test)
    plt.scatter(y_test, pred, s=4, alpha=0.4)
    plt.plot([0, 5], [0, 5], color='red')
    plt.xlabel('Real price ($100k)'); plt.ylabel('Predicted price ($100k)')
    plt.show()

    You should see: A cloud of dots along a diagonal line. Dots far from the line are the model's biggest mistakes.

  8. Find what matters most

    Ask the forest which clues it relied on.

    Copy this code
    imp = pd.Series(forest.feature_importances_, index=X.columns).sort_values(ascending=False)
    print(imp.round(3))

    You should see: Income (MedInc) at the top, followed by location (Latitude, Longitude).

  9. Predict a new house

    Take one test house, change its income value and see how the price moves.

    Copy this code
    house = X_test.iloc[[0]].copy()
    print('Predicted:', round(forest.predict(house)[0] * 100000), 'dollars')
    house['MedInc'] = house['MedInc'] + 2
    print('With higher income:', round(forest.predict(house)[0] * 100000), 'dollars')

    You should see: Two predicted prices: higher income gives a higher price, just as the data suggested.

  10. Explain it in your own words

    In a text cell, write 4 lines: the goal, the data, which model won, and one limitation (e.g. the data is from 1990).

    You should see: A short write-up that turns your notebook into a portfolio piece.

Level up

  • Try GradientBoostingRegressor and compare its error.
  • Remove the location columns and see how much worse the model gets.
  • Ask an AI chatbot to explain any line of code you don't understand.

Lessons behind this project

Show it off

Finished? Post about it on LinkedIn. Here's a starting point; add a screenshot and your own words.

Copy this post
I trained my first machine learning models today! Linear regression vs random forest on real housing data: the forest cut the error by about a third. Learned step by step with AI From Zero.
Share on LinkedIn

Add it to your portfolio

Employers love seeing what you've built. Use these ready-made texts, then add your own results and a screenshot.

1. A line for your CV or LinkedIn "Projects" section

Copy for your CV
Your first machine learning model: predict house prices: A model that predicts house prices in California from things like income and rooms, and a comparison of two algorithms. Skills: Loading and exploring a dataset, Splitting data into training and test sets, Training linear regression and random forest, Measuring error and making a prediction. Tools: Google Colab (free, runs in your browser with a Google account). No installation..

2. A README for GitHub

Create a free GitHub account, make a new repository, add a file called README.md and paste this in along with your notebook (File → Download → .ipynb).

Copy README.md
# Your first machine learning model: predict house prices

Train, test and improve a real machine learning model on real housing data, one small code cell at a time.

## What I built
A model that predicts house prices in California from things like income and rooms, and a comparison of two algorithms.

## What I learned
- Loading and exploring a dataset
- Splitting data into training and test sets
- Training linear regression and random forest
- Measuring error and making a prediction

## Tools
Google Colab (free, runs in your browser with a Google account). No installation.

## How it works
1. Open a notebook
2. Load the data
3. Explore it
4. Split into training and test data
5. Train linear regression
6. Try a random forest
7. See predictions vs reality
8. Find what matters most
9. Predict a new house
10. Explain it in your own words

## Results
(Add a screenshot and 2–3 sentences about what you found. Never include API keys or personal data.)

## Next steps
- Try GradientBoostingRegressor and compare its error.
- Remove the location columns and see how much worse the model gets.
- Ask an AI chatbot to explain any line of code you don't understand.

---
Built by following the free guided project at https://learnaifromzero.com/projects/house-price-model.html