Sub topic 6
Heuristics and the Existing System as Baselines
This chapter assumes you can fit and score a scikit-learn model, that you know the difference between a training split and a held-out test split, and that you have already chosen a metric for your task. Earlier chapters covered trivial baselines such as the majority class and the median. Here you will build baselines from human knowledge and from the system that is already running.
Why a heuristic belongs in the baseline set
A trivial baseline tells you whether the model has learned anything. A heuristic baseline tells you whether it has learned anything that people did not already know. Those are different questions. A model can beat the majority class easily and still lose to a one-line rule that an analyst wrote in an afternoon.
A heuristic is a fixed rule based on domain knowledge. An existing system is whatever currently makes the decision: a rule engine, a vendor tool, a spreadsheet, or a team of people. Both are baselines because they set the cost of not building the model. If the new model cannot clearly beat them, the project is not adding value, whatever it scores against a dummy predictor.
| Baseline | Example | Main strength | Main risk |
|---|---|---|---|
| Domain rule | Flag orders over a set amount from new customers | Cheap, explainable, no training data needed | Thresholds tuned on the test set |
| Lookup or lag rule | Predict last week's value for the same weekday | Captures seasonality for free | Hard to beat for stable series |
| Legacy model | The scoring system currently in production | Defines the real bar the business uses | Its logged outputs may be biased or incomplete |
| Human performance | Reviewers labeling the same items | Gives a realistic target | Reviewers disagree, so it is noisy |
Turning a heuristic into something you can score
Write the heuristic as an estimator with fit and predict. It then goes through the same split, the same metric and the same cross-validation code as the model. This removes a common source of unfair comparisons, where the rule is judged by eye and the model by a metric.
The example below uses synthetic order data. The rule flags an order when the amount is above a high quantile and the customer has few prior orders. The quantile is learned from training data only, so the rule does not see the test split.
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import balanced_accuracy_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
n = 4000
amount = rng.lognormal(mean=3.5, sigma=1.0, size=n)
prior_orders = rng.poisson(5, size=n)
logit = -7 + np.log(amount) - 0.25 * prior_orders
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
X = np.column_stack([amount, prior_orders])
class AmountRule(BaseEstimator, ClassifierMixin):
"""Flag large orders from customers with few prior orders."""
def __init__(self, quantile=0.9, max_orders=2):
self.quantile = quantile
self.max_orders = max_orders
def fit(self, X, y):
self.classes_ = np.unique(y)
self.threshold_ = np.quantile(X[:, 0], self.quantile)
return self
def predict(self, X):
flagged = (X[:, 0] > self.threshold_) & (X[:, 1] < self.max_orders)
return flagged.astype(int)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
models = {
"rule": AmountRule(),
"logreg": make_pipeline(
StandardScaler(), LogisticRegression(class_weight="balanced")
),
}
for name, model in models.items():
pred = model.fit(X_train, y_train).predict(X_test)
print(
name,
"balanced accuracy:", round(balanced_accuracy_score(y_test, pred), 3),
"recall:", round(recall_score(y_test, pred), 3),
)The rule has two parameters, quantile and max_orders. If you choose them by trying values and keeping the one that scores best on the test split, the rule is no longer a baseline. It has become a model fitted to the test set, and it will look stronger than it is.
Using the existing system as the baseline
When a system already makes the decision, it is almost always the baseline that matters most. The business compares your model with it, not with a dummy predictor. To use it you need its predictions for the same items as your test set, recorded at the time it made them. If you can only recompute its output afterwards with newer inputs, you are scoring a different system.
Three issues come up repeatedly.
- Different operating points. A legacy system usually makes a hard decision, such as flag or no flag, at a fixed threshold. A model gives a score, and you can pick any threshold. Comparing the model's accuracy at a threshold of 0.5 with the legacy system's behavior says little. Compare at a matched operating point: the same flag rate, the same recall, or the same precision.
- Biased labels. If labels come from a review process that only examines items the legacy system flagged, the unflagged items have no true label. The legacy system then looks better than it is, because its misses are never discovered. Reviewing a small random sample of unflagged items fixes this.
- Feedback loops. If the system's decisions change the data you see, for example by blocking transactions that would have turned out fraudulent, the labels you collected are partly a product of the baseline. Keep a small holdout where the baseline's action is not applied, if that is safe and permitted.
The function below compares a legacy score and a candidate score at the legacy system's own flag rate. This answers the question the business cares about: with the same review workload, how many true cases does each system catch?
import numpy as np
def recall_at_flag_rate(y_true, scores, flag_rate):
"""Recall when only the top flag_rate share of items is flagged."""
k = int(round(flag_rate * len(scores)))
top = np.argsort(-scores)[:k]
return y_true[top].sum() / y_true.sum()
rng = np.random.default_rng(1)
n = 5000
y_true = (rng.random(n) < 0.05).astype(int)
legacy = rng.normal(size=n) + 1.0 * y_true
candidate = rng.normal(size=n) + 1.5 * y_true
# The legacy system flags anything with a score above 2.0.
flag_rate = (legacy > 2.0).mean()
print("flag rate:", round(flag_rate, 3))
print("legacy recall: ", round(recall_at_flag_rate(y_true, legacy, flag_rate), 3))
print("candidate recall:", round(recall_at_flag_rate(y_true, candidate, flag_rate), 3))Both systems are scored on identical items with an identical number of flags. Any difference in recall is therefore a difference in ranking quality, not in how many items each one chose to flag.
Choosing which baseline to build first
You do not need every baseline. The diagram shows an order that keeps effort low while still producing the one comparison that matters.
If an existing system and a heuristic are both available, keep both. The existing system tells you what you must beat to replace it. The heuristic tells you how much of the gain comes from knowledge a person could write down, which is useful when you later decide whether the model's added complexity is justified.
Common errors
- Weakening the baseline on purpose. A rule with an arbitrary threshold, or a legacy system scored with a stale feature, makes any model look good. Give the baseline the same care you give the model.
- Scoring on different data. If the legacy predictions cover only a subset of the test items, restrict the model's score to that subset as well, or report both.
- Ignoring ties. Rules often produce few distinct scores. When you rank items for a flag-rate comparison, many tied items make the cutoff arbitrary. Break ties consistently, or report the flag rate you actually achieved.
- Comparing a decision with a probability. Accuracy at a default threshold is not a fair comparison with a hard rule. Use threshold-free metrics, or match operating points.
- Forgetting that the baseline has costs. A rule engine needs maintenance and a human review step costs time. Record these, because a later chapter weighs them against the model's gain.
Summary of the working model
A heuristic or existing system is a baseline only if it is scored under the same conditions as the candidate: the same held-out items, the same metric, and a matched operating point. Fix its parameters without using the test split. Check that the labels used for scoring are not produced by the baseline itself. Express the result in terms the system's owner already tracks.
Exercise
A fraud team's legacy rules flag 3% of transactions, and only flagged transactions are sent to investigators, who produce the labels. You train a model and score it on transactions the investigators labeled. It beats the legacy rules on recall. Name two reasons this comparison may be unfair and one change that fixes each.
Show answer
First, the labels exist mostly for transactions the legacy rules flagged, so frauds the rules miss are rarely labeled. This inflates the legacy recall and makes the comparison unreliable in both directions. A random sample of unflagged transactions sent to investigators fixes it. Second, the model is probably scored at a different operating point than the legacy rules, which flag exactly 3%. Fix this by flagging the top 3% of model scores and comparing recall at that same flag rate.
Exercise
You wrote a rule with a threshold and chose the threshold that gave the highest balanced accuracy on the test split. Why is this a problem, and how should you choose it instead?
Show answer
The test split was used to select the threshold, so the rule's test score is optimistic and the baseline looks harder to beat than it truly is. Choose the threshold on training data or a separate validation split, then score the rule once on the test split, as you do for the model.