AI and machine learning · Beginner · 22 min
Predict a number with regression in scikit-learn
By Padding · Updated 18 Nov 2026
Python 3.15 · scikit-learn 1.9.1 · pandas 3.1.1 · matplotlib 3.11.2
You will train a model that predicts delivery times in minutes, prove it beats a do-nothing baseline on held-out orders, and use a residual plot to find where it is still wrong.
On this page
A delivery app shows "arriving in 35 minutes" before the rider has left. That number is a prediction, and making it is a regression problem: from things you know when the order comes in (distance, number of items, the hour, the city), predict a quantity you only learn later (how many minutes the delivery took).
In this tutorial you build that prediction with scikit-learn. You generate 3,000 past deliveries, keep a quarter of them aside for testing, and start with a model that ignores every input and always answers with the average. Then you fit a linear regression and a random forest, measure all three in minutes with MAE and RMSE, and plot the errors to see which deliveries each model gets wrong and why. Along the way you see the rule this whole field rests on: a model's score means nothing until you compare it with a model that knows nothing.
The data is generated, so you know the true pattern behind it and can check that what the models learn is real. Everything runs on a laptop CPU in a few seconds, offline once the libraries are installed.
Step 1 · Create the project and install the libraries
Make a throwaway folder with its own virtual environment:
mkdir -p ~/delivery-times-demo
cd ~/delivery-times-demo
python3 -m venv .venv
source .venv/bin/activateInstall pinned versions of scikit-learn, pandas, matplotlib and NumPy, so your results match the ones in this tutorial:
pip install --quiet scikit-learn==1.9.1 pandas==3.1.1 matplotlib==3.11.2 numpy==2.5.5The download is about 100 MB, most of it NumPy and SciPy (which scikit-learn needs). On prepaid mobile data, run this on Wi-Fi; it is a one-off per project.
Check it worked
python -c "import sklearn, pandas, matplotlib, numpy; print(sklearn.__version__, pandas.__version__, matplotlib.__version__, numpy.__version__)"The output is 1.9.1 3.1.1 3.11.2 2.5.5. If you see No module named sklearn, the virtual environment is not active: run source .venv/bin/activate again in this terminal.
Step 2 · Generate 3,000 past deliveries
Each row is one finished delivery with four inputs and the answer, minutes. The generator builds the answer from a known recipe: a fixed 10 minutes for pick-up and hand-over, 3 minutes per kilometre, a little over a minute per item to pack, and random noise. Rush hour (8 to 9 in the morning, 5 to 7 in the evening) adds time per kilometre, and how much depends on the city's traffic. That last part matters later: it is a pattern a straight-line model cannot express.
cat > make_data.py <<'PY'
import numpy as np
import pandas as pd
rng = np.random.default_rng(11)
N = 3000
CITIES = ["Lagos", "Nairobi", "Accra", "Lisbon"]
# How much slower traffic is in each city at rush hour.
RUSH_FACTOR = {"Lagos": 2.0, "Nairobi": 1.6, "Accra": 1.3, "Lisbon": 1.0}
city = rng.choice(CITIES, size=N, p=[0.35, 0.25, 0.2, 0.2])
distance_km = rng.gamma(shape=2.0, scale=2.5, size=N).round(1) + 0.5
items = rng.integers(1, 9, size=N)
hour = rng.integers(8, 23, size=N)
rush = np.isin(hour, [8, 9, 17, 18, 19])
factor = np.array([RUSH_FACTOR[c] for c in city])
minutes = (
10 # pick-up and hand-over
+ 3.0 * distance_km # riding time
+ 1.2 * items # packing
+ rush * factor * 1.8 * distance_km # rush hour hurts long trips most
+ rng.normal(0, 4, size=N) # everything else
).clip(min=5).round(1)
df = pd.DataFrame(
{"distance_km": distance_km, "items": items, "hour": hour, "city": city, "minutes": minutes}
)
df.to_csv("deliveries.csv", index=False)
print(f"wrote {len(df)} deliveries")
print(df.describe().round(1))
PY
python make_data.py
head -4 deliveries.csvThe seed (default_rng(11)) fixes the random numbers, so you get the same 3,000 rows every time.
Check it worked
The script prints wrote 3000 deliveries and a summary table. The minutes column has a mean of about 37.3 and a maximum around 170: a few long rush-hour trips in heavy traffic. head shows the header distance_km,items,hour,city,minutes and rows such as 2.2,2,20,Lagos,18.3.
The noise has a standard deviation of 4 minutes. No model can predict that part, so even a perfect model would be off by about 3 minutes on average. Keep that floor in mind when you read the scores.
Step 3 · Split the data and score a baseline that knows nothing
A model is useful only if it predicts deliveries it has not seen. So hold back 25% of the rows as a test set, train on the rest, and score only on the test rows. Put the shared code in one module that the later scripts import:
cat > prepare.py <<'PY'
import pandas as pd
from sklearn.metrics import mean_absolute_error, root_mean_squared_error
from sklearn.model_selection import train_test_split
FEATURES = ["distance_km", "items", "hour", "city"]
def to_features(df):
# One column per city, holding 0 or 1, because models need numbers.
return pd.get_dummies(df[FEATURES], columns=["city"], dtype=int)
def load_split():
df = pd.read_csv("deliveries.csv")
X = to_features(df)
y = df["minutes"]
return train_test_split(X, y, test_size=0.25, random_state=42)
def score(name, y_true, y_pred):
mae = mean_absolute_error(y_true, y_pred)
rmse = root_mean_squared_error(y_true, y_pred)
print(f"{name:<18} MAE {mae:5.1f} min RMSE {rmse:5.1f} min")
return mae, rmse
PYTwo scores, both in minutes:
- MAE (mean absolute error) is the average size of the miss. An MAE of 5 means predictions are off by 5 minutes on a typical order.
- RMSE (root mean squared error) squares each miss before averaging, so a few big misses push it up much more than many small ones. When RMSE is far above MAE, some predictions are badly wrong.
Now the baseline. DummyRegressor ignores the inputs and always predicts the average delivery time from the training data. It is the "estimate" a shop gives without any model at all:
cat > baseline.py <<'PY'
from sklearn.dummy import DummyRegressor
from prepare import load_split, score
X_train, X_test, y_train, y_test = load_split()
print(f"train rows: {len(X_train)} test rows: {len(X_test)}")
print("columns:", list(X_train.columns))
baseline = DummyRegressor(strategy="mean")
baseline.fit(X_train, y_train)
print(f"baseline always predicts {baseline.predict(X_test[:1])[0]:.1f} minutes")
mae, rmse = score("baseline (mean)", y_test, baseline.predict(X_test))
assert len(X_test) == 750
assert 10 < mae < 16, mae
PY
python baseline.pyCheck it worked
You see train rows: 2250 test rows: 750 and seven columns: distance_km, items, hour and one city_ column per city. The baseline predicts about 37.4 minutes for every order and scores something like MAE 12.8 min RMSE 17.0 min. That is the number to beat. Any model that cannot get its MAE well under 12.8 minutes is adding complexity for nothing.
Step 4 · Fit linear regression and a random forest
Now train two real models on the same split and score them next to the baseline:
- Linear regression learns one number per column, the minutes it adds per unit, plus a starting value. Its prediction is a weighted sum, so it can only draw straight-line relationships.
- Random forest builds 200 decision trees, each on a random sample of the training rows, and averages their answers. Trees split the data with yes-or-no questions such as "is the hour 17 or later?", so the forest can learn that distance costs more at rush hour.
cat > compare.py <<'PY'
import joblib
from sklearn.dummy import DummyRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from prepare import load_split, score
X_train, X_test, y_train, y_test = load_split()
models = {
"baseline (mean)": DummyRegressor(strategy="mean"),
"linear regression": LinearRegression(),
"random forest": RandomForestRegressor(
n_estimators=200, min_samples_leaf=5, random_state=42, n_jobs=-1
),
}
results = {}
for name, model in models.items():
model.fit(X_train, y_train)
results[name] = score(name, y_test, model.predict(X_test))
linear = models["linear regression"]
print("\nlinear regression: minutes added per unit of each column")
for column, coef in zip(X_train.columns, linear.coef_):
print(f" {column:<14} {coef:+6.2f}")
print(f" {'(intercept)':<14} {linear.intercept_:+6.2f}")
joblib.dump(models["linear regression"], "linear.joblib")
joblib.dump(models["random forest"], "forest.joblib")
base_mae = results["baseline (mean)"][0]
assert results["linear regression"][0] < base_mae
assert results["random forest"][0] < results["linear regression"][0]
PY
python compare.pymin_samples_leaf=5 stops any tree from memorising single deliveries, and random_state=42 makes the forest the same on every run. The two trained models are saved with joblib (installed with scikit-learn) so the next steps can reuse them. Only load joblib files you made yourself: loading one runs Python's pickle, which can execute code from the file.
Check it worked
Three score lines print, something like:
baseline (mean) MAE 12.8 min RMSE 17.0 min
linear regression MAE 7.4 min RMSE 9.5 min
random forest MAE 3.8 min RMSE 4.9 minLinear regression cuts the typical miss from about 13 minutes to about 7. The forest gets to under 4, close to the 3-minute noise floor. Below the scores are the linear model's weights: distance_km is about +4.03 minutes per kilometre and items about +1.37 per item. The recipe used 3.0 per kilometre; the model inflated it to soak up the rush-hour delay it has no column for. The hour weight is small and negative, because one straight line through the hours cannot capture a delay at both ends of the day.
Step 5 · Plot the residuals to see where each model is wrong
A single MAE hides where the misses are. A residual is the actual time minus the predicted time: positive means the delivery took longer than promised. Plot residuals against predictions for both models, then group them by rush hour:
cat > residuals.py <<'PY'
import joblib
import matplotlib
matplotlib.use("Agg") # write files, no window needed
import matplotlib.pyplot as plt
import pandas as pd
from prepare import load_split
X_train, X_test, y_train, y_test = load_split()
linear = joblib.load("linear.joblib")
forest = joblib.load("forest.joblib")
fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
table = pd.DataFrame({"hour": X_test["hour"], "distance_km": X_test["distance_km"]})
for ax, (name, model) in zip(axes, [("linear regression", linear), ("random forest", forest)]):
predicted = model.predict(X_test)
residual = y_test - predicted # positive: the delivery took longer than predicted
table[name] = residual
ax.scatter(predicted, residual, s=8, alpha=0.4)
ax.axhline(0, color="black", linewidth=1)
ax.set_title(name)
ax.set_xlabel("predicted minutes")
axes[0].set_ylabel("actual minus predicted (minutes)")
fig.tight_layout()
fig.savefig("residuals.png", dpi=120)
print("saved residuals.png")
table["rush_hour"] = table["hour"].isin([8, 9, 17, 18, 19])
print("\nmean error by rush hour (positive = late against the prediction)")
print(table.groupby("rush_hour")[["linear regression", "random forest"]].mean().round(1))
long_rush = table[table["rush_hour"] & (table["distance_km"] > 8)]
print(f"\nrush-hour trips over 8 km: {len(long_rush)}")
print(long_rush[["linear regression", "random forest"]].mean().round(1))
linear_gap = table.groupby("rush_hour")["linear regression"].mean()
assert linear_gap[True] > 3 and linear_gap[False] < -1
PY
python residuals.pyCheck it worked
Open residuals.png from the ~/delivery-times-demo folder in any image viewer. The left panel (linear regression) splits into two fans that widen to the right: one band of points above the zero line and one below. The right panel (random forest) is a single, narrower cloud centred on zero. A healthy residual plot looks like the right one: no shape, just noise.
The table explains the two fans. Linear regression is about 10 minutes late on average at rush hour and about 5 minutes early the rest of the day: it averaged the two situations into one compromise. On rush-hour trips over 8 km it is late by around 18 minutes, exactly the orders where a customer is most likely to complain. The forest's averages stay within a minute of zero in every group.
Check the file from the terminal too:
python -c "data = open('residuals.png', 'rb').read(); print(data[1:4].decode(), len(data) > 20_000)"It prints PNG True.
Step 6 · Catch a model that beats nothing
A score on its own can fool you. Suppose a colleague trains a model on the hour and the city only, because those are known before the address is typed in. It reports an MAE of 12.7 minutes, which sounds like a working model. Compare it with the baseline:
cat > nothing.py <<'PY'
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
from prepare import load_split
X_train, X_test, y_train, y_test = load_split()
base = DummyRegressor(strategy="mean").fit(X_train, y_train)
base_mae = mean_absolute_error(y_test, base.predict(X_test))
candidates = {
"hour only": ["hour"],
"hour and city": ["hour", "city_Accra", "city_Lagos", "city_Lisbon", "city_Nairobi"],
"all columns": list(X_train.columns),
}
print(f"{'features':<14} {'MAE':>5} improvement on baseline ({base_mae:.1f} min)")
improvement = {}
for name, columns in candidates.items():
model = LinearRegression().fit(X_train[columns], y_train)
mae = mean_absolute_error(y_test, model.predict(X_test[columns]))
improvement[name] = 1 - mae / base_mae
print(f"{name:<14} {mae:5.1f} {improvement[name]:6.1%}")
assert improvement["hour only"] < 0.05
assert improvement["all columns"] > 0.3
PY
python nothing.pyCheck it worked
The table shows hour only and hour and city at about 12.7 minutes, an improvement of under 1% on the baseline, and all columns at about 7.4, an improvement of around 42%. The first two models produce different numbers for different orders, and they look like predictions, but they are no more useful than quoting the average. Report every model's score next to the baseline's, as a share of improvement, and treat anything close to 0% as a model that has learned nothing.
Step 7 · Predict new orders and know the limits
Use the saved forest for orders that have not happened yet. New rows must go through the same get_dummies step and end up with exactly the training columns, in the same order; reindex adds any missing city column as zeros. The last order is deliberately longer than any trip in the training data:
cat > predict.py <<'PY'
import joblib
import pandas as pd
from prepare import load_split, to_features
X_train, X_test, y_train, y_test = load_split()
forest = joblib.load("forest.joblib")
linear = joblib.load("linear.joblib")
orders = pd.DataFrame(
{
"distance_km": [3.0, 3.0, 12.0, 40.0],
"items": [2, 2, 5, 3],
"hour": [14, 18, 18, 14],
"city": ["Lagos", "Lagos", "Nairobi", "Accra"],
}
)
# Same columns, in the same order, as the training data.
X_new = to_features(orders).reindex(columns=X_train.columns, fill_value=0)
orders["forest"] = forest.predict(X_new).round(0)
orders["linear"] = linear.predict(X_new).round(0)
print(orders.to_string(index=False))
print(f"\nlongest trip in training data: {X_train['distance_km'].max()} km")
assert orders.loc[1, "forest"] > orders.loc[0, "forest"] + 3 # rush hour costs time
assert orders.loc[3, "forest"] < 110 # a forest cannot go past what it has seen
PY
python predict.pyCheck it worked
The table has one row per order with both models' estimates. The same 3 km Lagos order is about 21 minutes from the forest at 14:00 and about 30 at 18:00; linear regression gives roughly 25 and 24, missing the rush hour entirely. The recipe's true averages are about 21 and 32.
The 40 km order is where both models break. The longest training trip was about 26.7 km. The forest answers around 95 minutes, because it can only average delivery times it has seen; linear regression extends its inflated slope to around 174. The recipe says about 134. Neither number should reach a customer. In a real app, check each order against the range of the training data and fall back to a manual estimate outside it.
When you are finished, delete the folder:
cd ~
rm -rf ~/delivery-times-demoNext steps
A single train and test split gives one score from one lucky or unlucky draw. Validate a model honestly with cross-validation shows how to get a score with a spread, so you know whether 3.8 against 7.4 minutes is a real difference.
The get_dummies and reindex steps here are easy to get wrong between training and prediction. Build a scikit-learn pipeline with ColumnTransformer puts that preparation inside the model so it is saved and applied in one piece.
If you need to explain what drives delivery times rather than predict them, with confidence intervals for each weight, read Fit and read a linear regression with statsmodels.
On your own data, start with the baseline, keep the test set untouched until the end, and plot the residuals before you trust any single number.
Related tutorials
- Validate a model honestly with cross-validationYou will score a scikit-learn model with k-fold cross-validation, report its mean and spread, choose stratified, grouped or time-ordered folds to match your data, and catch two planted leaks that make a model look better than it is.
- Build a scikit-learn pipeline with ColumnTransformerYou will have one scikit-learn pipeline that imputes, scales and one-hot encodes a mixed customer table, trains a churn model, survives cross-validation and unseen categories, and is saved and reloaded with skops instead of pickle.
- Fit and read a linear regression with statsmodelsYou will fit an ordinary least squares model of maize yield with the statsmodels formula API, read its coefficients, intervals and R-squared, watch a confounder flip a coefficient, check the residuals and write up what the model says without claiming cause.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials