Sub topic 1
Start with the question: what are you predicting and why?
Model selection starts before any model exists. The choice of target, metric, and constraints narrows the candidate list more than any benchmark does. This chapter covers how to frame a tabular problem so that later choices (validation, baselines, model families) follow from it.
Prerequisites
This chapter assumes you know the following:
- Basic Python and pandas: loading a table, selecting columns, and filtering rows.
- Supervised learning basics: features, labels, and the split between training and test data.
- scikit-learn's
fitandpredictinterface.
You do not need to know any specific model yet. Later chapters introduce each family.
Why framing comes first
A model is a function from feature columns to a target column. Three decisions fix what "a good model" means:
- What the target is, and how it is defined.
- What decision the prediction will support.
- What it costs to be wrong, and in which direction.
If you skip these, you can tune a model for weeks and still deliver something nobody can use. Most failed tabular projects fail here, not in the choice between a random forest and a linear model.
Classification or regression
The first split is the type of target.
| Target | Task | Example | Typical output |
|---|---|---|---|
| Category with two values | Binary classification | Will this customer cancel? | Probability of the positive class |
| Category with many values | Multiclass classification | Which product tier will they buy? | One probability per class |
| Continuous number | Regression | How much will they spend next month? | A number |
| Count or ordered value | Regression variants | Number of support tickets | A non-negative number |
The same business question can often be framed more than one way. "Will this customer churn?" is binary classification. "When will this customer churn?" is a survival or time-to-event problem. "How much revenue will we lose to churn?" is regression. Each framing needs different labels, a different metric, and a different validation scheme.
Two cautions about reframing:
- Do not bin a continuous target without a reason. Turning "spend" into "high or low" discards information. Do it only if the decision really is binary, such as a fixed threshold in a policy.
- Do not treat an ordered target as plain classes by accident. Ratings from 1 to 5 can be modeled as regression or as classification. The choice affects how errors are penalized, because predicting 4 for a true 5 is less wrong than predicting 1.
Define the target precisely
The target column is rarely given. You build it from raw events, and that definition contains choices that change the problem.
Questions to settle in writing:
- Observation window. What period of history may the features use?
- Prediction horizon. How far ahead are you predicting? "Churn within 30 days" and "churn within 12 months" are different targets.
- Label timing. When does the true label become known? If it takes 90 days, you cannot train on the most recent 90 days of rows.
- Unit of prediction. Is a row a customer, an order, or a customer-month? The unit decides how rows relate to each other, which matters for validation.
Identify the decision
A prediction is useful only if it changes what someone does. Ask:
- Who acts on the prediction? A person reviewing a queue, an automated system, or a customer-facing screen.
- What action follows? Send an offer, flag a transaction, order stock.
- Is a ranking enough, or do you need calibrated probabilities? If you contact the top 500 customers per week, only the ordering matters. If you set a price from the predicted probability, the probability itself must be accurate.
- How often will it run? A nightly batch job and a 50 ms web request have very different limits on model size.
These answers feed directly into the metric (next chapters but one) and into the practical constraints chapter near the end of this tutorial.
Cost of errors
Errors are rarely symmetric. In a fraud screen, a missed fraud costs far more than a false alarm. In a marketing campaign, a wasted offer costs a little and a missed buyer costs a missed sale.
A simple way to make this concrete is to write the cost of each outcome as a table:
| Row | Predicted positive | Predicted negative |
|---|---|---|
| Actually positive | Benefit of acting (true positive) | Cost of a miss (false negative) |
| Actually negative | Cost of a wasted action (false positive) | No cost (true negative) |
You do not need exact numbers. Rough ratios, such as "a miss costs about ten times a false alarm", are enough to choose between metrics and to set a decision threshold later.
Class balance matters here too. If 2% of rows are positive, a model that always predicts "negative" is 98% accurate and useless. Check the class balance during framing so that you do not pick accuracy by habit.
import pandas as pd
# A small example table with a binary target.
df = pd.DataFrame({
"customer_id": range(1, 9),
"tenure_months": [3, 24, 12, 48, 5, 36, 7, 60],
"churned": [1, 0, 0, 0, 1, 0, 1, 0],
})
print(df["churned"].value_counts())
print(df["churned"].value_counts(normalize=True).round(3))On real data, the printed share of the positive class tells you how imbalanced the problem is. Record it in your framing notes.
Check that the problem is worth modeling
Before building anything, check three things.
- Is there a simple rule that already works? A business rule such as "flag orders above a set amount" is your first baseline. A model must beat it to justify its cost.
- Is there enough labeled data? A rough guide: rare positive classes need enough positives, not just enough rows. 100,000 rows with 30 positives is a small dataset for classification.
- Will the data you train on look like the data you predict on? If the process changes (new pricing, a new customer segment), past patterns may not hold. This is distribution shift.
From framing to model choice
Framing does not pick a model by itself, but it removes many options and sets the criteria for the rest.
Some examples of how framing narrows the choice:
- A regulator requires a reason for each decision. Interpretable models, or models paired with explanation tools, move to the front.
- Predictions must run in a few milliseconds on a small server. Large ensembles become harder to justify.
- The target is a rare event with costly misses. You need a metric that is sensitive to the positive class, and you may need to tune the decision threshold.
- Rows are grouped, for example many orders per customer. Validation must keep each group together, which affects every comparison that follows.
A framing checklist
Write the answers down before you open a notebook. A short document is enough.
- The business question in one sentence.
- The target: type, definition, horizon, and when the label becomes known.
- The unit of prediction (one row means what?).
- The action that follows a prediction, and who takes it.
- The relative cost of each error type.
- The positive class rate.
- The existing rule or process to beat.
- A list of columns that might not be available at prediction time.
- Hard constraints: latency, explainability, data privacy, retraining frequency.
Common mistakes
- Starting from the model. "Let's try gradient boosting" before the target is defined leads to rework.
- Optimizing a convenient proxy. You may predict clicks because clicks are logged, when the real goal is purchases. A model can win on the proxy and lose on the goal.
- Ignoring time. If the data is ordered in time, a random split lets the model see the future. Framing should flag this so validation can use time-aware splits.
- Letting the label definition drift. If the definition of "churn" changes midway, old and new rows mean different things.
- Assuming the data table is the problem. Sometimes the right answer is that the labels are too noisy or the signal is too weak. A framing step that ends with "do not model this yet" is a good outcome.
Exercise
A retailer wants to predict which customers will return an item. Rows are customer orders, and a return can be reported up to 45 days after delivery. List two framing decisions you must make before training, and name one column that could cause target leakage.
Show answer
Two decisions: (1) the prediction horizon and label timing, for example "returned within 45 days", which means orders from the last 45 days have unknown labels and must be excluded from training; (2) the decision the prediction supports, such as whether to show a stricter return policy at checkout, which fixes the cost of false positives and false negatives. A leaky column is "return shipping label created", because it is generated only after the customer starts a return, so it would not be available when the prediction is made.
Exercise
In a dataset where 1% of rows are positive, a model that always predicts the negative class reaches 99% accuracy. Why does this matter during framing, and what should you record before choosing a metric?
Show answer
It shows that accuracy can hide a useless model when classes are imbalanced. During framing you should record the positive class rate and the relative cost of false negatives and false positives. These let you choose a metric that reflects the real goal, such as one based on ranking or on the positive class, instead of defaulting to accuracy.