Exercise: How Many Loaves?
Write four plain-Python functions that hold back Sunrise Bakery's last two weeks as test days, guess them with the average and with a weekday rule learned from the training days, and measure each guess's average miss, and let pytest check the split, the arithmetic and that no test day goes into a guess.
Apprentice · AI Basics · Python · Updated
Sunrise Bakery's owner wants to know, honestly, whether the weekday averages are worth baking by. You'll write the four functions that answer it: one that holds the last two weeks back as test days, one for the baseline guess, one for the weekday rule, and one that measures how far off a set of guesses is. It's all plain Python, lists and dictionaries, with no machine learning library yet: the ideas come first. Tests call each function and check what it gives back.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-ml-how-many-loaves, 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-how-many-loaves.git
Git makes a folder, exercise-ml-how-many-loaves, 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:
bakery_days.csv: the 120 days, 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.loaves.py: the four functions, for you to finish, andload_days, which reads the CSV into a list of dictionaries, ready to use.report.py: holds back the last two weeks, guesses them both ways with your 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 120 days. You don't need to change them.requirements.txtandpytest.ini: the packages the exercise needs, at exact versions (pytest, and NumPy forseed_data.pyonly), and where pytest finds the tests and your code.
What to do
Every function in loaves.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. A day is a dictionary such as {"day": 6, "weekday": "Saturday", "high_temp_f": 72, "is_holiday": 0, "loaves_sold": 143}:
def mean_miss(guesses, actual):
"""Return the average miss: for each day, the distance between its guess and what it
really sold, as a positive number, averaged over the days. Not rounded.
guesses and actual are lists of the same length, in the same order of days.
mean_miss([100, 110], [90, 130]) -> 15.0 (misses of 10 and 20)
mean_miss([140.0], [140]) -> 0.0
"""
raise NotImplementedError("Not built yet.")
In each function, replace the raise NotImplementedError("Not built yet.") line with your own code:
hold_out_last(days, n)returns two lists,train, test: the lastndays as the test days, and every day before them as the training days, both still in time order. It doesn't changedays. With the 120 days andnof 14: 106 training days (days 1 to 106) and 14 test days (days 107 to 120).average_guess(train)returns the baseline: the averageloaves_soldof the training days, not rounded. Days that sold 90, 96 and 84 loaves give90.0.weekday_rule_guess(day, train)returns the averageloaves_soldof the training days with the same"weekday"asday, not rounded: training Saturdays of 143, 139 and 138 loaves give140.0for a Saturday. It uses onlyday["weekday"], neverday["loaves_sold"], which is the answer the guess is scored against. If no training day has that weekday, it returnsaverage_guess(train).mean_miss(guesses, actual)returns the average miss: for each day, the distance between the guess and what it sold, as a positive number, averaged. Guesses of 100 and 110 against 90 and 130 sold give15.0.
The split comes first, and both guesses learn from the training days only: that's what keeps the test days ones the guesses never saw.
Check your work
Run the tests from the exercise folder, with the virtual environment on:
python -m pytest
At first all 15 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(test) after hold_out_last(days, 14) should return 14, but it returned 106. No test checks how good the guesses are: the tests check the split, the arithmetic, and that no test day ever goes into a guess.
To see your functions at work on the whole file, run python report.py.
Hints
- Look before you write. Open
bakery_days.csvin VS Code and read the last few rows: those are the dayshold_out_lastholds back. - Two slices. Negative positions count from the end of a list, as Training and Testing: Never Grade Your Own Homework shows, so the last
nitems and the items before them are two slices. A slice is a new list, sodaysstays as it was. - An average is a total and a count. Pick out the
loaves_soldyou need with a loop or a list comprehension, then divide the total by how many there are, as The Simplest Guess: Baselines does. - Only the same weekday. In
weekday_rule_guess, anifthat compares each training day's"weekday"withday["weekday"]picks the days that count. Check for an empty list before you divide. - Pair them up.
zip(guesses, actual)gives each day's guess and real loaves together in aforloop, andabs()turns a difference into a positive miss.
When you're done
Every test is green: pytest's last line says 15 passed. And python report.py prints:
1) days: 120
2) training days: 106
3) test days: 14 (day 107 to day 120)
4) the average guess: 100.0
5) the average guess, average miss on the test days: 16.6
6) the weekday rule, guess for day 113 (a Monday): 93.6
7) the weekday rule, average miss on the test days: 6.9
The weekday rule's misses are well under half the baseline's: knowing the day of the week is worth something. Now look at day 113, a holiday Monday that sold 117 loaves. How far off was the weekday rule's guess, and which column in the file could help a better rule see that day coming?
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-how-many-loaves), 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-how-many-loaves.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-how-many-loaves, 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
Hold the newest days back, make the simplest guess and a better one from the training days only, and score both on the days they never saw: that's the honest test every model in this course has to pass, written here in a few lines of plain Python.