Exercise: Home Price Guesser
Write three functions that split Maple Grove's 400 home sales into training and test homes with no home on both sides, train a LinearRegression on the training homes, and guess prices for new homes, and let pytest check the split, the model and the guesses.
Journeyman · AI Basics · Python · Updated
A family in Maple Grove wants a fair price for their home, and the town's 400 past sales are the examples to learn from. You'll write the three functions behind a first price model: one that splits the sales into homes to learn from and homes to test on, one that trains a linear regression, and one that turns it into guesses. Tests call each function and check what it gives back, and a notebook comes with the exercise for looking at the data while you work.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-ml-home-price-guesser, also linked from the Exercise box beside the lesson. Clone it into your python-course folder. In VS Code's terminal:
cd ~/python-course
git clone https://github.com/ask-codey/exercise-ml-home-price-guesser.git
Git makes a folder, exercise-ml-home-price-guesser, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment. On Windows (PowerShell):
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
On a Mac (zsh):
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
The prompt starts with (.venv) once the virtual environment is on. The exercise's README says what each command does, and what to do if PowerShell won't run the second one.
The folder holds:
home_sales.csv: the 400 sales, our own made-up data, the same file the chapter's lessons use.seed_data.py: the script that made the CSV, with the pattern it planted. You don't need to run it: the committed CSV is what keeps everyone's numbers the same.price_model.py: the three functions, for you to finish, withFEATURES(the columns the model looks at:size_sqft,garage_spacesandage_years) andLABEL(sale_price), ready to use.explore.ipynb: a notebook for looking at the sales and trying your code. Choose the.venvkernel with Select Kernel (top right) before you run it. The tests don't read it.report.py: splits, trains and guesses with your three functions and prints what each step gave. Ready to use.tests/: the tests, which call each function and check what comes back, andconftest.py, which gives each test a fresh copy of the sales. You don't need to change them.requirements.txtandpytest.ini: the packages the exercise needs, at exact versions, and where pytest finds the tests and your code.
What to do
Every function in price_model.py is already declared with its name and parameters, and for now it stops with a NotImplementedError that says Not built yet. The docstring under each one says what it should do, with examples:
def predict_prices(model, homes):
"""Return the model's guesses for a table of homes, as a list of whole dollars.
homes may have more columns than the model learned from (home_id, bedrooms,
sale_price and so on): give the model only the FEATURES columns. Round each
guess to a whole number of dollars with round().
With a model that learned 50,000 + 135 a square foot + 9,000 a garage space
- 800 a year of age:
a home of 2,000 square feet, 2 garage spaces, 10 years old -> [330000]
a home of 1,250 square feet, no garage, 41 years old -> [185950]
"""
raise NotImplementedError("Not built yet.")
In each function, replace the raise NotImplementedError("Not built yet.") line with your own code:
split_homes(homes, seed)splits the sales into four parts withtrain_test_split: theFEATUREScolumns asX, theLABELcolumn asy, a fifth of the homes held back for testing, andseedpassed on asrandom_state. It returnsX_train, X_test, y_train, y_test. With seed 42: 320 training homes, 80 test homes, and no home in both.train_price_model(X, y)makes aLinearRegression, fits it toXandy, and returns the fitted model. Given homes that sold for exactly $50,000 plus $135 a square foot plus $9,000 a garage space minus $800 a year of age, it learns the coefficients 135, 9000 and −800 and the intercept 50000.predict_prices(model, homes)gives the model only theFEATUREScolumns ofhomes, and returns its guesses as a list of whole dollars:[330000]for a 2,000-square-foot home with 2 garage spaces, 10 years old, with the exact model above.
The split comes first, and train_price_model is only ever given the training homes: that's what keeps the test homes ones the model never saw.
Check your work
Run the tests from the exercise folder, with the virtual environment on:
python -m pytest
At first all 14 tests fail. That's expected: each function you finish turns its tests green. A failing test's message says what it called, what it expected and what came back, for example len(X_test) after split_homes(homes, 42) should return 80, but it returned 100. No test checks how close the guesses come to the real prices, which depends on each sale's random wobble: the tests check the split, the model and the arithmetic.
To see your functions at work on the whole file, run python report.py.
Hints
- Look before you write. Run the notebook's first cells:
homes.head(10)andhomes.describe()show the columns and their ranges. - Four parts, in a fixed order.
train_test_splitgives back the training features, the test features, the training labels and the test labels, as Splitting Data with train_test_split shows. A fifth istest_size=0.2. - Make, fit, return. Your First scikit-learn Model: fit and predict has the three steps;
train_price_modelneeds the first two, then hands the model back. - Two pairs of brackets.
homes[FEATURES]is a table of the three feature columns, whatever other columnshomeshas, and in the order the model learned them. - One guess per home.
predictgives back an array; aforloop that rounds each guess withround()and adds it to a list (or a list comprehension) turns them into whole numbers.
When you're done
Every test is green: pytest's last line says 14 passed. And python report.py prints:
1) homes: 400
2) training homes: 320
3) test homes: 80
4) dollars per unit of size_sqft: 135.57
5) dollars per unit of garage_spaces: 7885.29
6) dollars per unit of age_years: -821.65
7) intercept: 49209.98
8) first three test homes, guessed: [333866, 301084, 211851]
9) first three test homes, sold for: [335000, 317500, 228000]
10) a 2,000 sq ft home, 2 garage spaces, 10 years old: 327909
Now compare lines 4 to 7 with what seed_data.py planted: $135 a square foot, $9,000 a garage space, −$800 a year and $50,000 to start. Which did the model get closest to? In the notebook, split with seed 7 instead of 42 and train again: what moves, and what stays about the same?
Submit your exercise
The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.
On GitHub, click +, then New repository. Name it (for example
exercise-ml-home-price-guesser), choose Public, and click Create repository. Leave out the README: your folder already has one.In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:
git remote set-url origin https://github.com/your-name/exercise-ml-home-price-guesser.git git add . git commit -m "My solution" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-ml-home-price-guesser, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.
Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.
So what
A split made before anything learns, a model trained on one side of it, and guesses made from exactly the columns it learned: that's the honest skeleton of every model in this course, and each function is small enough to test.