Exercise: Lemonade Stand Forecast
Hold back some of a lemonade stand's summer for testing, train a straight-line model with scikit-learn on the rest, turn temperatures into guesses, and measure how far off they are, while pytest checks each function.
Apprentice · Python · AI Basics · Updated
Jada, who runs the Sunny Days Lemonade Stand, wants a forecast she can plan with: how many cups to make tomorrow, and how far off that guess tends to be. You'll write the four functions behind it with scikit-learn: one holds some of last summer's days back, one trains a straight-line model on the rest, one turns temperatures into guesses, and one measures the guesses on the days the model never saw.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-python-lemonade-stand-forecast, 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-python-lemonade-stand-forecast.git
Git makes a folder, exercise-python-lemonade-stand-forecast, with the exercise code inside. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment, the same three steps as in the exercises before. 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
This time requirements.txt installs scikit-learn and pandas as well as pytest, and they bring NumPy and a few other packages with them, so the last command takes a minute or two. The prompt starts with (.venv) once the virtual environment is on.
The folder holds:
forecast.py: the four functions, for you to finish. The imports they need are already at the top.report.py: prints the stand's forecast with your functions, so you can see them at work. Ready to use.lemonade_days.csv: the stand's summer, 92 days with the temperature (temp_f) and the cups sold (cups_sold), the same made-up days as the lessons. Ready to use.seed_data.py: the script that made the CSV, with the pattern built in. You don't need to run it.tests/test_forecast.py: the tests, which call each function and check what comes back. You don't need to change it.requirements.txtandpytest.ini: the packages the tests need, and where pytest finds the tests and your code.
What to do
Every function in forecast.py is 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 mean_error(actual, guesses):
"""Return the mean absolute error: how many cups a guess is off by, on average.
Each guess's miss is how far it is from the actual cups, counted as a
positive number whether the guess was too high or too low. The mean
absolute error is the average of those misses. Round it to 1 decimal place.
mean_error([50, 60, 70], [52, 57, 70]) -> 1.7 (misses 2, 3 and 0: 5 / 3 = 1.666...)
mean_error([80, 80], [90, 70]) -> 10.0 (one 10 too high, one 10 too low)
"""
raise NotImplementedError("Not built yet.")
In each function, replace the raise NotImplementedError("Not built yet.") line with your own code:
split_days(days, seed)takes the stand's table and returnsX_train, X_test, y_train, y_test: thetemp_fcolumn as a one-column table for the features, thecups_soldcolumn for the label, with a fifth of the days held back (test_size=0.2) andseedpassed on asrandom_state. With the 92 days, that's 73 to learn from and 19 held back.train_model(X, y)makes aLinearRegressionmodel, fits it toXandy, and returns the fitted model. On days that sold exactly 2 cups a degree minus 80, it learns a slope of 2 and a starting point of −80.predict_cups(model, temps)takes a list of temperatures, such as[70, 90], and returns the model's guesses as a list of whole cups:[60, 100]for that 2-cups-a-degree model.mean_error(actual, guesses)returns the mean absolute error of two lists, rounded to 1 decimal place, as its docstring shows.
Each function returns its answer. None of them prints anything: the tests read what comes back.
Check your work
Run the tests from the exercise folder, with the virtual environment on:
pytest
At first all 16 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 mean_error([80, 80], [90, 70]) should return 10.0, but it returned 0.0.
The tests check the split's sizes, that no day lands in both parts, and that your seed gives the same split as random_state does. They check the model's slope on days with no wobble, where the right answer is known exactly. The last test trains on the real summer with seed 42 and checks that the guesses on the held-back days are off by less than 10 cups on average; the fixed seed makes that number the same on every run.
To see your functions at work, run python report.py. It prints the stand's forecast from your four functions.
Hints
- The split is one call.
train_test_splitalready gives back the four parts in the ordersplit_daysreturns them. How to Tell When a Model Is Wrong shows the call. - Two pairs of brackets for the features.
days[["temp_f"]]is a one-column table, which is what scikit-learn wants;days["cups_sold"]is the label's single column. A Model That Guesses explains the difference. - fit, then return the model.
fitchanges the model it's called on, sotrain_modelreturns the model itself. - Match the column name.
predictneeds a table with the same column name the model learned from:pd.DataFrame({"temp_f": temps})builds one from a list. - Misses don't cancel. A guess too high and one too low both count as misses, so take each one's size with
abs(), or let scikit-learn'smean_absolute_errordo the arithmetic. Work the docstring's first example through by hand first.
When you're done
Every test is green: pytest's last line says 16 passed. And python report.py prints:
Sunny Days Lemonade Stand: the forecast
Learned from 73 days; tested on 19 days it never saw
Cups per degree: 1.74
Off by 7.9 cups a day on average, on the days it never saw
At 72 degrees: about 67 cups
At 81 degrees: about 82 cups
At 90 degrees: about 98 cups
The error is 7.9, not the 8.1 in How to Tell When a Model Is Wrong, because predict_cups rounds each guess to whole cups before mean_error measures it. Now look back at the report: the model learned 1.74 cups a degree from 73 days, and the pattern built into the data was 2. What would you expect the slope to be if Jada had five summers of days instead of one?
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-python-lemonade-stand-forecast), 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-python-lemonade-stand-forecast.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-python-lemonade-stand-forecast, 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 back, train, guess, measure: those four steps are how a model is built and judged honestly, whether it guesses cups of lemonade or delivery times, and you wrote each of them.