Module 4 · Beginner · How models learn and why they fail

Baseline models: the score every model must beat

Baseline models in machine learning with Python: DummyRegressor, DummyClassifier, mean vs median, rule baselines, and how to tell if a model is worth it.

By theprogrammers team · · 14 min read

A friend says their new cricket prediction app is "70% accurate" at picking match winners. Impressive? Not if the home team wins 65% of the time anyway. Anyone who always picks the home team gets 65% with no app at all. The app is only adding 5 points, and you'd never know without that comparison.

A baseline model is that comparison: the score of the simplest possible approach, worked out before you build anything clever. In machine learning, baseline models are the score every model must beat. Without one, a number like "MAE ₹8,000" or "accuracy 78%" means nothing: you can't tell whether the model learned anything. Below you'll build the standard baselines for regression and classification in scikit-learn, and meet the uncomfortable cases where a simple rule almost matches a full model.

What you need first: how machine learning models learn, loss functions explained and the scikit-learn tutorial.

Key terms

  • Baseline: a very simple method whose score sets the bar a real model must clear.
  • Dummy model: a baseline that ignores the features completely, such as "always predict the average".
  • Rule baseline (or heuristic): a simple rule a person might use, such as "flag anyone with glucose above 140".
  • Persistence baseline: for time series, "tomorrow will be the same as today".
  • Lift over baseline: how much better the model is than the baseline, in the units you care about.

The simplest prediction: one number for everyone

Before any data science, imagine predicting a flat's monthly rent with no information about the flat at all. You'd still give your best single guess. Here are five rents in a neighbourhood, in thousands of rupees:

FlatRent (₹ thousand)
A12
B14
C15
D16
E43

What single number should you guess for every flat? Two natural choices are the mean (12 + 14 + 15 + 16 + 43) ÷ 5 = 20, and the median, the middle value, 15. Which is better depends on how you measure error. Work out both by hand:

  • Guess 20 for every flat. Absolute errors: 8, 6, 5, 4, 23. Mean absolute error (MAE) = 46 ÷ 5 = 9.2.
  • Guess 15 for every flat. Absolute errors: 3, 1, 0, 1, 28. MAE = 33 ÷ 5 = 6.6.

The median wins on MAE. Now check squared errors in Python:

import numpy as np

rent = np.array([12, 14, 15, 16, 43])
for name, guess in [("mean", rent.mean()), ("median", np.median(rent))]:
    errors = rent - guess
    mae = np.abs(errors).mean()
    mse = (errors ** 2).mean()
    print(f"guess the {name} ({guess:.0f}): MAE {mae:.1f}   MSE {mse:.1f}")
guess the mean (20): MAE 9.2   MSE 134.0
guess the median (15): MAE 6.6   MSE 159.0

On MSE (mean squared error) the mean wins instead. This isn't a coincidence, and it's worth remembering:

  • The median is the single number with the lowest MAE. One huge rent (₹43k) doesn't drag it.
  • The mean is the single number with the lowest MSE. Squaring makes the ₹43k flat's error count so much that the best guess moves towards it.

So the right dummy baseline matches your metric: the median for MAE, the mean for MSE and R². Loss functions explained shows why the two losses behave so differently.

Regression baselines with DummyRegressor

DummyRegressor is scikit-learn's "one number for everyone" model. It has the usual fit and predict, but fit only learns that one number from the training labels, and predict ignores the features. On the California housing data (median house value per district, in units of $100,000):

Download the data: california-housing.csv (1.9 MB), or from the original source, the StatLib repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("california-housing.csv").

import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_absolute_error

X, y = fetch_california_housing(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

def mae_dollars(predictions):
    return f"${mean_absolute_error(y_test, predictions) * 100_000:,.0f}"

for strategy in ["mean", "median"]:
    dummy = DummyRegressor(strategy=strategy).fit(X_train, y_train)
    print(f"always predict the {strategy:6} ({dummy.constant_[0][0]:.2f}): MAE {mae_dollars(dummy.predict(X_test))}")
always predict the mean   (2.07): MAE $91,382
always predict the median (1.81): MAE $87,987

strategy="median" predicts the median of the training labels; constant_ holds the number it learned. As the rent example predicted, the median gives a lower MAE. So this is the bar: a model that doesn't beat an MAE of about $88,000 has learned nothing useful from the eight features.

Now a real model:

from sklearn.linear_model import LinearRegression

linear = LinearRegression().fit(X_train, y_train)
print("linear regression: MAE", mae_dollars(linear.predict(X_test)))
linear regression: MAE $53,690

The error drops by about $34,000 per district, a big improvement. That difference, not the $53,700 on its own, is what tells you the model is working.

A model that barely beats the baseline

Here's what failure looks like. Suppose you only had one feature, the age of the houses:

age_only = LinearRegression().fit(X_train[["HouseAge"]], y_train)
print("house age only:  MAE", mae_dollars(age_only.predict(X_test[["HouseAge"]])))
house age only:  MAE $90,767

This "model" has a fitted weight and an intercept, and its predictions vary from district to district, so it looks like it's doing something. But it's barely better than the mean, and worse than the median. Without the baseline, you might report "MAE $90,800" and think you had a model. Checking the baseline first protects you from fooling yourself.

Rule baselines: what would a person do?

Dummy models are the lowest bar. A stronger, more honest bar is a simple rule that someone with domain knowledge would use. For house prices, an estate agent might say: "Districts where people earn more have pricier houses. Group districts by income and use the typical price of each group."

Predict: linear regression uses all eight features. Will a one-feature rule like this be far behind it, or close?

income_bands = pd.qcut(X_train["MedInc"], q=10)                 # 10 equal-sized income groups
typical_value = y_train.groupby(income_bands, observed=True).median()

test_bands = pd.cut(X_test["MedInc"], bins=income_bands.cat.categories)
rule_predictions = test_bands.map(typical_value).astype(float)
rule_predictions = rule_predictions.fillna(y_train.median())     # incomes outside the training range
print("income-band rule: MAE", mae_dollars(rule_predictions))
income-band rule: MAE $63,434

What each line does:

  • pd.qcut(..., q=10) cuts the training incomes into 10 groups with the same number of districts in each.
  • groupby(...).median() finds the typical house value in each group, from training rows only, so nothing leaks from the test set.
  • pd.cut(..., bins=income_bands.cat.categories) puts each test district into the same groups, using the training group edges.
  • fillna(...) handles test incomes below the lowest or above the highest training income, which fall outside every group.

The rule is much better than the dummy and closer to linear regression than you might expect. Linear regression's lead over the rule is about $10,000 per district. That's still worth having, but it's the honest measure of what the extra seven features and the model add.

The four results side by side. This is the picture to keep: a model's score means something only next to the baselines.

Bar chart of mean absolute error on California house prices. Always predicting the median, the dummy baseline, gives $87,987. The income-band rule gives $63,434. Linear regression with eight features gives $53,690. A model using only house age gives $90,767, worse than the dummy baseline. A dashed line at the dummy baseline marks the bar every model must get below.

Classification baselines with DummyClassifier

For classifiers, the dummy strategies are:

StrategyWhat it predicts
"most_frequent"Always the most common class
"stratified"Random classes, in the same proportions as the training labels
"uniform"Random classes, each equally likely
"constant"Always the class you choose with constant=

The Pima diabetes data has 768 women; about 35% were diagnosed with diabetes.

Download the data: pima-diabetes.csv (35 KB), or from the original source, OpenML. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("pima-diabetes.csv").

The helper below reports accuracy and recall, the share of diabetic women the model actually finds. Recall matters here because missing a diabetic patient is the costly mistake. (Classification metrics covers recall properly.)

from sklearn.datasets import fetch_openml
from sklearn.dummy import DummyClassifier

X_pima, y_pima = fetch_openml("diabetes", version=1, as_frame=True, return_X_y=True)
y_pima = (y_pima == "tested_positive").astype(int)
P_train, P_test, q_train, q_test = train_test_split(
    X_pima, y_pima, test_size=0.25, random_state=0, stratify=y_pima)

def report(name, predicted):
    accuracy = (predicted == q_test).mean()
    recall = predicted[q_test == 1].mean()
    print(f"{name:22} accuracy {accuracy:.3f}   diabetic women found {recall:.0%}")

for strategy in ["most_frequent", "stratified", "uniform"]:
    dummy = DummyClassifier(strategy=strategy, random_state=0).fit(P_train, q_train)
    report(strategy, dummy.predict(P_test))
most_frequent          accuracy 0.651   diabetic women found 0%
stratified             accuracy 0.531   diabetic women found 33%
uniform                accuracy 0.552   diabetic women found 60%

The most_frequent dummy scores 65% accuracy by saying "not diabetic" to everyone, and finds no diabetic women at all. That's the trap with accuracy when one class is more common: a useless model can look decent. The random strategies find some patients only by luck. (random_state=0 makes their random guesses repeatable.)

A one-line medical rule

A doctor's simple rule: the 2-hour glucose test (plas in this data) is normally below 140 mg/dL, so flag anyone at 140 or above.

glucose_rule = (P_test["plas"] >= 140).astype(int)
report("glucose >= 140 rule", glucose_rule)
glucose >= 140 rule    accuracy 0.766   diabetic women found 57%

One comparison, no training, and it's far better than any dummy. Now the real model: logistic regression on all eight features, with scaling. (Logistic regression adds up weighted features and turns the total into a probability; the logistic regression module builds it from scratch.)

Predict: with eight features instead of one, how much better than the glucose rule will it be?

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

logistic = make_pipeline(StandardScaler(), LogisticRegression()).fit(P_train, q_train)
report("logistic regression", logistic.predict(P_test))
logistic regression    accuracy 0.781   diabetic women found 58%

Barely better. On 192 test patients, 1.5 points of accuracy is three more correct answers, and the recall difference is one more patient found. That's within the range of luck from one split. The honest summary: this model hasn't yet shown that it beats a rule any nurse could apply. That's not a failure of the lesson; it's exactly what baselines are for. It tells you to look for better features, try other models, or accept the rule, which is free to run and easy to explain.

Experiment: change the rule's threshold from 140 to 120, and run report again. More women are flagged, so recall goes up and accuracy goes down. Choosing a threshold is a decision about which mistake is worse, the same idea as framing a problem.

The persistence baseline for time series

When predicting something over time (tomorrow's price, next week's sales), the classic baseline is persistence: "tomorrow will be the same as today". It's surprisingly hard to beat for many real series:

rng = np.random.default_rng(0)
price = 40 + np.cumsum(rng.normal(0, 0.8, size=730))     # two years of a drifting daily price
tomorrow_actual = price[1:]
tomorrow_guess = price[:-1]                                # today's price
print(f"persistence baseline: off by ₹{np.abs(tomorrow_actual - tomorrow_guess).mean():.2f} per day")
persistence baseline: off by ₹0.64 per day

price[1:] is every day from the second onwards, and price[:-1] is every day except the last, so each guess is paired with the following day. A forecasting model for this price has to beat ₹0.64 a day to be worth anything. For a price that drifts randomly like this one, it almost certainly can't.

How to choose your baselines

Use at least two: a dummy (the floor) and a rule (the honest bar).

ProblemDummy baselineRule baseline ideas
Regression, MAEDummyRegressor(strategy="median")Typical value per group (city, income band, category)
Regression, MSE or R²DummyRegressor(strategy="mean")Same, using group means
ClassificationDummyClassifier(strategy="most_frequent")One threshold on the strongest feature
Time seriesPersistence (today's value)Same day last week, or last year
Ranking or recommendationsMost popular itemsItems similar to the last one bought

Calculate baselines first, on the same split and metric as your models, and include them in every comparison table you report.

Common mistakes

  • No baseline at all. "Accuracy 78%" sounds good until you learn the most common class is 65% and a one-line rule gets 77%.
  • The wrong dummy for the metric. For MAE, the median baseline is stronger than the mean. Compare against the strongest simple option, not the weakest.
  • Building the rule with test data. Group medians, thresholds and bands must come from training rows only.
  • Celebrating tiny wins. A gain of 1 or 2 points on a small test set can be luck. Cross-validation, later in this module, shows how to tell.
  • Ignoring cost. A model only slightly better than a free, explainable rule may not be worth deploying.

Practice

  1. Marks in a class test are 4, 6, 7, 7 and 26 out of 30. What single guess has the lowest MAE, and what single guess has the lowest MSE? Work it out, then check with NumPy.
Show the answer

The median, 7, gives the lowest MAE. The mean, (4 + 6 + 7 + 7 + 26) ÷ 5 = 10, gives the lowest MSE.

marks = np.array([4, 6, 7, 7, 26])
for guess in [7, 10]:
    print(guess, np.abs(marks - guess).mean(), ((marks - guess) ** 2).mean())
7 4.6 74.2
10 6.4 65.2

The guess of 7 has the lower MAE; the guess of 10 has the lower MSE. The one high mark (26) pulls the mean up and costs it on MAE.

  1. A spam filter reports 90% accuracy on an inbox where 88% of emails are not spam. What baseline should you compare it with, and what would you conclude?
Show the answer

DummyClassifier(strategy="most_frequent"), which always says "not spam" and scores 88%. The filter only adds 2 points over doing nothing. You'd also check how much of the spam it actually catches (recall), since "never flag spam" catches none.

  1. Predict, then run: what accuracy and recall does the glucose rule get with a threshold of 120?
Show the answer
report("glucose >= 120 rule", (P_test["plas"] >= 120).astype(int))
glucose >= 120 rule    accuracy 0.703   diabetic women found 75%

Lowering the threshold flags more women. Recall rises sharply, because many diabetic women have glucose between 120 and 140. Accuracy falls, because more non-diabetic women are flagged too. Which threshold is better depends on the cost of each mistake.

  1. Why must the income bands and their median values come only from the training rows?
Show the answer

The band medians are the rule's "predictions". If they were calculated with test rows, the test districts' own house values would help predict themselves, which is leakage. The rule would look better than it really is, and the comparison with the model would be unfair.

  1. Your new model for daily vegetable prices has an MAE of ₹0.70 per kg. The persistence baseline is ₹0.64. What do you tell your manager?
Show the answer

That the model is worse than simply using today's price as tomorrow's prediction, so it shouldn't be used as it is. Either it needs better features (weather, festival dates, arrivals at the market) or the price is mostly random from day to day, in which case persistence is the sensible choice.

  1. Why is a rule baseline more useful than a dummy baseline when deciding whether to deploy a model?
Show the answer

A dummy only shows the model learned something. A rule shows whether the model beats what people could already do cheaply. If a model is barely better than a simple, explainable rule, the rule may be the better choice: it's free, transparent and doesn't need retraining.

Interview questions

What is a baseline model and why is it important?

A baseline is the simplest reasonable predictor, such as always predicting the mean or the most frequent class, or a simple domain rule. It gives a reference score: a model's value is its improvement over the baseline, not its raw score. It also catches bugs and leakage: a model far worse than the baseline is broken, and one far better than any sensible expectation may be leaking.

Which constant minimises mean absolute error, and which minimises mean squared error?

The median minimises MAE, because moving the guess towards the middle reduces the total absolute distance. The mean minimises MSE, because squared errors are minimised where the derivative of the sum of squared differences is zero, which is at the mean.

Key takeaways

  • A score means nothing alone; report it next to a baseline on the same split and metric.
  • Dummy baselines ignore features: the median for MAE, the mean for MSE, the most frequent class for classifiers.
  • Rule baselines are the honest bar: the glucose ≥ 140 rule nearly matched an eight-feature model.
  • Persistence ("tomorrow = today") is the baseline for time series, and it's often hard to beat.
  • Build baselines from training data only, and treat tiny wins over them with suspicion.

Frequently asked questions

What is a good baseline score?

There's no universal number. A good baseline is the strongest simple method for your problem: usually a dummy model plus a rule an expert would use. Your model is good if it clearly beats them, by a margin bigger than the normal variation between splits.

What does DummyClassifier do in scikit-learn?

It's a classifier that ignores the features and predicts using a simple strategy: the most frequent class, random classes in the training proportions, uniformly random classes, or a fixed class. Its score is the floor any real classifier must beat.

What if my model can't beat the baseline?

Check for bugs first (misaligned rows, wrong labels, bad preprocessing). If there are none, the features may not contain enough information to predict the label. Try better features or more data, or use the simple rule.

What to learn next

  1. Overfitting and underfitting: when a model learns too little or too much.
  2. Loss functions explained: why MAE and MSE prefer different baselines.
  3. Cross-validation explained: tell a real improvement from luck.