Sub topic 1
Start with the question: framing the problem and the target
Most failed machine learning projects fail before any model is trained. The team answers a question nobody asked, or defines the label so that it cannot be known when a prediction is needed. This chapter covers the decisions that come first: what you are predicting, for whom, when, and how you will judge success.
Prerequisites
This chapter assumes you have:
- Basic Python and pandas, including filtering rows and boolean masks.
- A rough idea of supervised learning: a model learns a mapping from input columns (features) to a known answer (the target, or label).
- Basic statistics, such as a mean and a class proportion.
No scikit-learn is needed yet. The later chapters build the pipeline.
From a business question to a learning task
A business question is usually phrased as a goal: "reduce customer churn" or "approve loans faster." A learning task is narrower. It names an input, an output, and a moment in time. To convert one into the other, write down four things:
- The unit of prediction. One row per customer, per transaction, per customer-month? This decides what a "sample" is.
- The decision it supports. Who acts on the prediction, and what do they do differently?
- The target. The exact quantity to predict, defined precisely enough that two people would compute the same value.
- The prediction moment. The point in time at which the prediction is made, and therefore which information is available.
If you cannot name the decision, the project has no way to be judged useful. A churn score that nobody acts on is a report, not a product.
Choosing the task type
The form of the target determines the family of models and metrics.
| Question | Target | Task type |
|---|---|---|
| Will this customer cancel within 90 days? | Yes or no | Binary classification |
| Which category does this support ticket belong to? | One of several labels | Multiclass classification |
| Which topics apply to this article? | Several labels at once | Multilabel classification |
| How much will this customer spend next month? | A number | Regression |
| How many days until this machine fails? | A number, possibly censored | Regression or survival analysis |
Reframing is a legitimate tool. "How much will a customer spend?" can become "Will spending exceed 100?" That is easier to model and may be enough for the decision. The cost is that you throw away information, and the threshold becomes a design choice you must defend.
Defining the target precisely
A vague target such as "churned" hides several decisions. Make each one explicit.
- Horizon. Churn within 30 days and churn within 90 days are different targets with different base rates.
- Observation window. Which past data may be used for features?
- Eligibility. Who can be predicted at all? A customer who already cancelled cannot churn again, so they should not be a row.
- Label source. Is the label observed directly, or is it a proxy? "Clicked" is a proxy for "interested." Models learn the proxy, not the thing you care about.
The following code builds a churn table from a raw event log. It fixes a snapshot date, uses only past events to decide eligibility, and uses only future events to define the label.
import pandas as pd
events = pd.DataFrame({
"customer_id": [1, 1, 2, 3, 3, 3, 4, 5],
"event_date": pd.to_datetime([
"2025-05-10", "2025-08-01", "2025-06-15", "2025-04-20",
"2025-06-10", "2025-09-01", "2025-01-05", "2025-06-20",
]),
})
snapshot = pd.Timestamp("2025-06-30")
lookback = pd.Timedelta(days=90)
horizon = pd.Timedelta(days=90)
# Eligible: active in the 90 days up to and including the snapshot.
past = events[
(events["event_date"] <= snapshot)
& (events["event_date"] > snapshot - lookback)
]
eligible = past["customer_id"].unique()
# Label: churned if no event in the 90 days after the snapshot.
future = events[
(events["event_date"] > snapshot)
& (events["event_date"] <= snapshot + horizon)
]
active_later = set(future["customer_id"])
table = pd.DataFrame({"customer_id": eligible})
table["churned"] = (~table["customer_id"].isin(active_later)).astype(int)
print(table)
print("churn rate:", table["churned"].mean())It prints four rows. Customers 1 and 3 have churned equal to 0, customers 2 and 5 have 1, and the churn rate is 0.5. Customer 4 was last active in January, so they are not eligible and never appear. That exclusion is a framing decision, not a data-cleaning accident.
Everything that feeds features must come from before the snapshot. Everything that defines the label must come from after it. Mixing the two is the most common way to build a model that looks excellent and does nothing in production.
Pitfalls in target definition
- Label leakage. A feature that is a consequence of the label. For example, a "cancellation_reason" column is filled in only after a customer cancels. Ask of every column: would this value exist at the prediction moment?
- Moving definitions. If the business changes what counts as "active" halfway through the history, the label means different things in different periods.
- Selection bias. Loan default is observed only for applicants who were approved. A model trained on them says nothing reliable about rejected applicants.
- Delayed labels. Recent rows may look like non-churners only because their horizon has not finished. Drop rows whose horizon extends past the end of your data.
- Noisy labels. Human-labeled data disagrees with itself. Measure agreement between labelers before treating labels as truth.
- Feedback loops. If predictions change behavior, for example a retention offer to high-risk customers, future labels are influenced by the model.
Class balance and what it implies
Check the target distribution immediately. With 2 percent positives, a model that always predicts "no" is 98 percent accurate and useless. Imbalance affects the choice of metric, the splitting strategy (stratification, covered in a later chapter), and how you interpret scores. Do not rebalance data at this stage. First decide what an error costs.
Choosing the success metric early
Write down the success metric before looking at results, for two reasons. It prevents you from picking whichever metric flatters the model afterward. It also forces the cost question: is a missed churner worse than a wasted retention offer?
A useful framing has two parts:
- A model metric, such as recall at a fixed precision, or mean absolute error. This is what you optimize and compare.
- A business outcome, such as retained revenue net of offer cost. This is what justifies the project.
They can disagree. A model with the best AUC may still lose money at the capacity your retention team has. If the team can contact only 500 customers a week, precision among the top 500 scores matters more than global ranking quality.
A short framing checklist
Before collecting data, answer these in writing:
- What decision will the prediction change, and who makes it?
- What is one row, and when is the prediction made?
- What exactly is the target, including horizon and eligibility?
- What data is available at that moment?
- What is the baseline today, such as a rule or a human guess?
- What metric and threshold count as success?
The baseline question matters more than it seems. If a simple rule already catches most of the benefit, a complex model may not justify its maintenance cost.
Exercise
A team wants to predict which hospital patients will be readmitted within 30 days. One proposed feature is "length of the follow-up appointment." Why is this a framing problem, and what should the team ask instead?
Show answer
A follow-up appointment happens after discharge, so its length is not known at the prediction moment, which is discharge. It leaks future information and would inflate offline scores while failing in use. The team should ask of every feature whether it exists at the time the prediction is made, and keep only those that do.
Exercise
In the churn code, the snapshot is 2025-06-30 and the horizon is 90 days. The event log ends on 2025-08-15. What is wrong, and how would you fix it?
Show answer
The horizon ends on 2025-09-28, after the data ends. Customers who would have been active in late August or September look like churners because those events are not yet recorded. Fix it by moving the snapshot back to at most 2025-05-17 (the log end minus 90 days), or by shortening the horizon to 46 days or fewer.