Predicting a Number
Classification predicts a category. Regression predicts a number: a
delivery time, a price, tomorrow's demand. The fit, predict and score
pattern stays the same, but judging the result changes. A predicted delivery
time is rarely exactly right, so instead of counting right and wrong answers
you measure how far predictions are from the truth.
Linear Regression
Linear regression predicts a number as a starting value plus one weight
times each feature. For delivery times, that could read: "10 minutes, plus 3
minutes per kilometre, plus 8 minutes per level of traffic". Training,
fit, finds the starting value and weights that make the predictions as close
as possible to the training labels; scikit-learn's LinearRegression uses the
method called ordinary least squares. After training, the weights are stored
in coef_, one per feature, in the order of the feature columns.
Because each weight is a number of minutes per unit of a feature, a linear model is easy to read: you can check whether its weights are plausible.
Mean Absolute Error
The mean absolute error (MAE) is the average distance between predictions and true values, ignoring whether a prediction was too high or too low:
MAE = the average of |prediction − true value| over the test samples
It is expressed in the units of the label. An MAE of 4 minutes means predictions are, on average, 4 minutes away from the actual delivery time. That makes it easy to judge against the real need: 4 minutes may be fine for a food delivery and useless for scheduling a train.
As always, compare with a baseline. DummyRegressor() predicts the training
average for every case; its MAE shows how far off you would be by ignoring the
features altogether.
Exercise: Predict Delivery Times
You will generate delivery data with a known pattern, train a linear model, and compare its error with the baseline's.
Starting state: the course environment, active in your terminal. The script generates its own data.
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/ai-practice/predict-delivery-times cd ~/ai-practice/predict-delivery-timesWindows PowerShell:
mkdir $HOME\ai-practice\predict-delivery-times cd $HOME\ai-practice\predict-delivery-timesSave this as
delivery_times.pyin that folder:"""Predict delivery times in minutes and judge the error against a baseline.""" import numpy as np from sklearn.dummy import DummyRegressor from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error from sklearn.model_selection import train_test_split # Generated deliveries: time grows with distance and with traffic, plus random variation. rng = np.random.default_rng(4) distance_km = rng.uniform(1, 20, size=500) traffic = rng.integers(0, 3, size=500) # 0 light, 1 normal, 2 heavy minutes = 10 + 3 * distance_km + 8 * traffic + rng.normal(0, 5, size=500) X = np.column_stack([distance_km, traffic]) X_train, X_test, y_train, y_test = train_test_split(X, minutes, random_state=4) baseline = DummyRegressor().fit(X_train, y_train) model = LinearRegression().fit(X_train, y_train) print(f"Baseline mean absolute error: {mean_absolute_error(y_test, baseline.predict(X_test)):.1f} minutes") print(f"Model mean absolute error: {mean_absolute_error(y_test, model.predict(X_test)):.1f} minutes") print("Learned minutes per km:", model.coef_[0].round(2), "| per traffic level:", model.coef_[1].round(2)) for predicted, actual in zip(model.predict(X_test[:3]), y_test[:3]): print(f"Predicted {predicted:5.1f}, actual {actual:5.1f}") -
Run it:
python delivery_times.pyOutput, which should match exactly:
Baseline mean absolute error: 16.5 minutes Model mean absolute error: 4.2 minutes Learned minutes per km: 2.94 | per traffic level: 8.15 Predicted 19.2, actual 24.0 Predicted 64.6, actual 69.8 Predicted 48.6, actual 52.2
How the Script Works
Generating the data. np.random.default_rng(4) creates a random-number
generator with a fixed seed, so the data is the same on every run.
rng.uniform(1, 20, size=500) draws 500 distances between 1 and 20 km,
rng.integers(0, 3, size=500) draws traffic levels 0, 1 or 2, and
rng.normal(0, 5, size=500) draws random variation centred on 0 with a
standard deviation of 5 minutes. The minutes line builds each delivery time
from a known rule: 10 minutes, plus 3 per kilometre, plus 8 per traffic level,
plus the variation. np.column_stack puts the two features side by side as
X.
Because you wrote the rule, you can check what the model learns. With real data, the rule is unknown; that is why you need a model.
Training and comparing. The data is split, then both the baseline and the
linear model are fitted on the training deliveries. mean_absolute_error
takes the true values first and the predictions second.
What the results show. The baseline is 16.5 minutes off on average; the model, 4.2 minutes. The learned weights, 2.94 minutes per km and 8.15 minutes per traffic level, are close to the 3 and 8 used to generate the data. They are not exact, because the random variation hides the rule slightly. The model's error cannot fall to zero either: the variation, with a standard deviation of 5 minutes, is genuinely unpredictable from the features, so no model could remove it. The three example predictions are each a few minutes off, as an MAE of 4.2 suggests.
If you changed the 5 in rng.normal(0, 5, size=500) to 1, the deliveries
would vary less around the rule, and the model's MAE would shrink
accordingly; the baseline's would barely change.
Success: the output matches; you can state the model's MAE in minutes and compare it with the baseline's, and you can relate the learned weights to the rule that generated the data.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
| Different numbers | The seed 4 or a random_state was changed | Restore the values shown |
ValueError: Found input variables with inconsistent numbers of samples | The features and labels have different lengths, for example after editing one size=500 | Use the same size everywhere |
| An MAE in the thousands | The arguments to mean_absolute_error include features instead of labels | Pass y_test and the predictions |
ModuleNotFoundError | The course environment is not active | Activate it and rerun |
-
Clean up. macOS and Linux:
cd ~/ai-practice ls rm -rf predict-delivery-times lsWindows PowerShell:
cd $HOME\ai-practice ls Remove-Item -Recurse predict-delivery-times lsCheck that the first
lsshowspredict-delivery-timesbefore removing it. Do the independent task first.
Independent task: change the script so that the model uses distance only.
Replace the line X = np.column_stack([distance_km, traffic]) with
X = distance_km.reshape(-1, 1), which makes a one-column feature table, and
change the Learned minutes per km line to
print("Learned minutes per km:", model.coef_[0].round(2)), because there is
now only one weight. Predict whether the model's error will rise or fall, then
run it.
Check Your Understanding
A delivery company's model has an MAE of 12 minutes; the mean baseline's MAE is 15 minutes.
- What does an MAE of 12 minutes mean in plain words?
- The company promises customers a one-hour delivery window. Is the model good enough for that promise? What about a promise of "within 5 minutes"?
- How much has the model improved on simply predicting the average?
Answer and Reasoning
Independent task
The model's MAE rises from 4.2 to 7.1 minutes. Without the traffic feature, the model cannot account for the 0, 8 or 16 extra minutes that traffic adds, so that part of the variation now counts as error. It is still far better than the baseline's 16.5 minutes, because distance explains most of the variation.
Understanding check
- On average, its predictions are 12 minutes away from the actual delivery times, sometimes early, sometimes late.
- For a one-hour window, an average error of 12 minutes may be acceptable, though some individual predictions will be further off, so the company should also look at the largest errors. For "within 5 minutes", no: the typical error alone is more than twice that.
- By 3 minutes on average, from 15 to 12: a modest improvement. Whether the model is worth using depends on what those 3 minutes are worth.