Sub topic 1
Why Every Project Starts with a Baseline
Prerequisites
This chapter assumes you know the following:
- Basic supervised learning: features, labels, training, and prediction.
- Common metrics such as accuracy, precision, recall, and mean absolute error (MAE).
- Basic Python and scikit-learn usage.
- Basic statistics: mean, standard deviation, and standard error.
What a baseline is
A baseline is a simple, cheap reference method that you score on your task before you build anything more complex. Its score is the number every later model has to beat.
A baseline answers one question: compared with what? A model with 92% accuracy tells you little by itself. If always predicting the most common class gives 91%, the model adds almost nothing. If a one-line rule gives 60%, the model adds a lot.
A baseline is not a weak model you try to beat for show. It is a measuring instrument. It fixes the scale you use to read every other result in the project.
Why it matters
A baseline does four jobs.
- It gives scores a meaning. A metric value only means something relative to a reference point.
- It checks your pipeline. If a trivial method scores very well, you likely have leakage, a label problem, or a metric that does not fit the task. If a complex model scores no better than a trivial one, the features may carry no signal, or the code may have a bug.
- It sets the stakes for added work. The gap between the baseline and your target tells you how much room an expensive model has to improve things.
- It is a fallback. A simple baseline that already works can ship while you iterate on something better.
Skipping the baseline is a common failure. A team spends weeks tuning a gradient-boosted model, reports a score, and then discovers that a rule or a linear model reaches nearly the same result. The extra weeks bought nothing.
The baseline workflow
The order below keeps the comparison fair. Later chapters cover each step in detail.
Two rules hold throughout:
- Choose the metric before you look at any score.
- Score every method on the same held-out data, so differences come from the methods and not from the data.
A worked example: accuracy can mislead
The next script builds a dataset where 95% of the examples belong to one class. It trains a baseline that always predicts the majority class, then scores it with two metrics.
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, balanced_accuracy_score
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=2000, weights=[0.95, 0.05], random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
pred = baseline.predict(X_test)
print("accuracy:", accuracy_score(y_test, pred))
print("balanced accuracy:", balanced_accuracy_score(y_test, pred))Expect accuracy near 0.95 and balanced accuracy of exactly 0.5.
Here is why the two differ:
DummyClassifier(strategy="most_frequent")ignores the features and always outputs the majority class.- Accuracy is the share of correct predictions. The baseline is right for every majority-class example, which is about 95% of the data.
- Balanced accuracy is the average of recall across classes. The baseline gets recall 1.0 on the majority class and 0.0 on the minority class, so the average is 0.5. That is the score of random guessing.
The model does nothing useful, yet it scores 95% accuracy. If your rare class is fraud, disease, or failure, that class is the whole point of the project. A candidate model that reaches 96% accuracy has not shown anything yet.
The example also uses stratify=y. This keeps the class proportions the same in the training and test sets. Without it, a small minority class can end up badly under-represented in the test set by chance.
Kinds of baselines
Different tasks and project stages call for different baselines. They form a ladder of increasing strength and cost.
| Kind | Examples | What it tells you |
|---|---|---|
| Trivial | Majority class, class prior, mean, median, previous value | The floor. Anything below it is broken. |
| Heuristic | A hand-written rule, a business threshold, the current production system | Whether machine learning beats what people already do |
| Simple model | Logistic or linear regression, a shallow decision tree | How much signal is in the features, with little tuning |
| Candidate model | Gradient boosting, neural networks | The result you want to justify |
Trivial baselines
A trivial baseline uses no features, or almost none. Use the one that fits the task:
- Classification: predict the most frequent class, or the class prior.
- Regression: predict the mean to minimize squared error, or the median to minimize absolute error.
- Forecasting: predict that the next value equals the previous one.
The regression case shows two baselines of different strength on one split. The median predictor ignores the features. The linear model uses them.
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
rng = np.random.default_rng(0)
X = rng.normal(size=(500, 3))
y = 3.0 * X[:, 0] - 2.0 * X[:, 1] + rng.normal(scale=1.0, size=500)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
for name, model in [
("median", DummyRegressor(strategy="median")),
("linear", LinearRegression()),
]:
model.fit(X_train, y_train)
mae = mean_absolute_error(y_test, model.predict(X_test))
print(name, round(mae, 3))Both models use the same split and the same metric (MAE). The linear model should show a much lower error, because the data is built from a linear signal. On real data the gap is rarely this clear, and that is exactly what the baseline helps you see.
For time series, the standard trivial baseline is the naive forecast: tomorrow equals today.
import numpy as np
# Daily values; the naive forecast predicts that tomorrow equals today.
y = np.array([102.0, 105.0, 103.0, 108.0, 110.0, 109.0, 113.0])
actual = y[1:]
naive_forecast = y[:-1]
mae = np.mean(np.abs(actual - naive_forecast))
print("naive MAE:", mae)This baseline is surprisingly hard to beat for series that change slowly. A forecasting model that cannot beat it is not worth deploying.
Heuristic and existing-system baselines
A heuristic baseline is a rule a person could write: "flag any transaction over $5,000," or "recommend the most popular items." If a system already runs in production, that system is your baseline. A new model must beat it on the same data and the same metric, and it must do so by enough to justify the cost of replacing it.
Simple-model baselines
A simple model such as logistic regression or a shallow tree is often the strongest baseline you can build in minutes. It needs little tuning and is easy to inspect. If a tuned ensemble beats it by only a little, the added complexity may not pay off.
Common errors
- Scoring the baseline on different data. If the baseline and the candidate use different splits, the gap contains split noise. Use the same split or the same cross-validation folds for both.
- Fitting anything on the test set. Computing a mean, a median, or the class prior on the full dataset leaks test information into the baseline.
DummyRegressorandDummyClassifierlearn these values from training data only, which is the safe pattern. - Using a baseline that is too weak. Beating a random guess is easy. Compare against the strongest baseline that is cheap to build.
- Treating one score as exact. A single train/test score has noise. A small gap may disappear on another split. Later chapters show how repeated cross-validation and paired comparisons address this.
- Choosing the metric last. See the callout above.
How baselines connect to the rest of the project
The baseline sets up every decision that follows in this tutorial:
- It fixes the metric and the splits that all later comparisons use.
- It provides the number a candidate must beat, and the noise level tells you by how much.
- Together with a performance ceiling such as human level, it brackets the range of possible improvement.
- It anchors the final good-enough decision. A model is good enough when its gain over the baseline meets requirements that were written down in advance.
The sections that follow cover metrics, splits, repeated cross-validation, and the criteria you apply when you decide to ship.
Exercise
A fraud-detection dataset has 1% fraud. A model scores 99.2% accuracy on the test set. A majority-class baseline scores 99.0%. What do you conclude, and what would you do next?
Show answer
The model is only 0.2 percentage points better than a baseline that never detects fraud, so accuracy tells you almost nothing here. Switch to a metric that reflects the rare class, such as recall, precision, or balanced accuracy, and score both the baseline and the model on the same split. The baseline will have recall 0 on fraud, so the comparison becomes informative. Also check that the model actually flags fraud cases.
Exercise
You are forecasting daily sales. Your new model has an MAE of 12.0. The naive forecast (tomorrow equals today) has an MAE of 11.5 on the same held-out period. Should you deploy the model?
Show answer
No. The model has a higher error than the trivial baseline on the same data and metric. It is more complex and no better. Look for problems in the features or setup, or keep the naive forecast, unless further work produces a clear gain.